Skip to content

Commit 848e56b

Browse files
committed
added solution for the autocomplete exercise - wesbos#6
1 parent 7a1ed7f commit 848e56b

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

06 - Type Ahead/index-START.html

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,41 @@
1717
<script>
1818
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
1919

20+
const cities = [];
21+
22+
fetch(endpoint)
23+
.then(blob => blob.json())
24+
.then(data => cities.push(...data)); //spread into an array
25+
26+
function findMatches (wordToMatch,cities) {
27+
return cities.filter(place => {
28+
//figure out if if city or state matches the search term
29+
const regex = new RegExp(wordToMatch, 'gi')
30+
return place.city.match(regex) || place.state.match(regex);
31+
});
32+
}
33+
34+
function displayMatches () {
35+
const matchArray = findMatches(this.value,cities);
36+
const html = matchArray.map(place => {
37+
const regex = new RegExp(this.value, 'gi');
38+
const cityName = place.city.replace(regex,`<span class="hl">${this.value}</span>`);
39+
const stateName = place.state.replace(regex,`<span class="hl">${this.value}</span>`)
40+
return `
41+
<li>
42+
<span class="name">${cityName}, ${stateName}</span>
43+
<span class="population">${place.population}</span>
44+
</li>
45+
`;
46+
}).join('');
47+
suggestions.innerHTML = html;
48+
}
49+
50+
const searchInput = document.querySelector('.search');
51+
const suggestions = document.querySelector('.suggestions');
52+
53+
searchInput.addEventListener('change', displayMatches);
54+
searchInput.addEventListener('keyup', displayMatches);
2055
</script>
2156
</body>
2257
</html>

0 commit comments

Comments
 (0)