Skip to content

Commit dd47213

Browse files
committed
finish JS30 wesbos#6
1 parent a1d44fd commit dd47213

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

06 - Type Ahead/index-START.html

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,13 +27,42 @@
2727
getCities().then(ret => cities.push(...ret));
2828

2929
function findMatches(wordToMatch, cities) {
30+
if (wordToMatch === "") return [];
3031
return cities.filter(place => {
3132

3233
const regex = new RegExp(wordToMatch, 'gi');
3334
return place.city.match(regex) || place.state.match(regex);
3435
})
3536
}
37+
38+
function numberWithCommas(x) {
39+
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
40+
}
41+
42+
function displayMatches() {
43+
const matchArray = findMatches(this.value, cities);
44+
const html = matchArray.map(place => {
45+
const regex = new RegExp(this.value, 'gi');
46+
const cityName = place.city.replace(regex, `<span class="hl">${this.value}</span>`);
47+
const stateyName = place.state.replace(regex, `<span class="hl">${this.value}</span>`);
48+
return `
49+
<li>
50+
<span class="name">${cityName}, ${stateyName}</span>
51+
<span class="population">${numberWithCommas(place.population)}</span>
52+
</li>
53+
`;
54+
}).join('');
55+
suggestions.innerHTML = html;
56+
57+
58+
}
3659

60+
const searchInput = document.querySelector('.search');
61+
const suggestions = document.querySelector('.suggestions');
62+
63+
searchInput.addEventListener('change', displayMatches);
64+
searchInput.addEventListener('keyup', displayMatches);
65+
3766

3867

3968
</script>

0 commit comments

Comments
 (0)