Skip to content

Commit c08944f

Browse files
committed
updated wesbos#6
1 parent 0bfeb9f commit c08944f

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

06 - Type Ahead/index-START.html

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,44 @@
1717
</form>
1818
<script>
1919
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
20+
const cities = [];
21+
fetch(endpoint)
22+
.then(blob => blob.json())
23+
.then(data => cities.push(...data))
2024

25+
function findMatches (wordToMatch, cities) {
26+
return cities.filter(place => {
27+
//here we need to figure out if the city or state matches what was searched
28+
const regex = new RegExp(wordToMatch, 'gi');
29+
return place.city.match(regex) || place.state.match(regex)
30+
});
31+
}
32+
33+
function numberwithCommas(x){
34+
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
35+
}
36+
function displayMatches() {
37+
const matchArray = findMatches(this.value, cities);
38+
const html = matchArray.map(place => {
39+
const regex = new RegExp(this.value, 'gi');
40+
const cityName = place.city.replace(regex, `<span class="hl">${this.value}</span>`);
41+
const stateName = place.state.replace(regex, `<span class="hl">${this.value}</span>`);
42+
return `
43+
<li>
44+
<span class = "name">${cityName}, ${stateName}</span>
45+
<span class = "population> ${numberwithCommas(place.population)}"</span>
46+
</li>
47+
`;
48+
}).join('');
49+
console.log(html);
50+
suggestions.innerHTML = html;
51+
}
52+
53+
const searchInput = document.querySelector('.search');
54+
const suggestions = document.querySelector('.suggestions');
55+
56+
searchInput.addEventListener('change', displayMatches);
57+
searchInput.addEventListener('keyup', displayMatches);
2158
</script>
2259
</body>
2360
</html>

0 commit comments

Comments
 (0)