Skip to content

Commit 197c564

Browse files
author
Arnab Majumdar
committed
1 parent 8348ef3 commit 197c564

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

06 - Type Ahead/index-START.html

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,55 @@
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(data => data.json())
24+
.then(data => cities.push(...data))
25+
26+
function findMatch(word, cities){
27+
return cities.filter(place => {
28+
const regex = new RegExp(word, 'gi'); //g - global, i = case insensitive
29+
return place.city.match(regex) || place.state.match(regex)
30+
});
31+
}
32+
function numberWithCommas(x) {
33+
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
34+
}
35+
36+
function displayItem(){
37+
const matchArr = findMatch(this.value, cities);
38+
console.log(matchArr);
39+
const html = matchArr.map(place => {
40+
// const placeName = place.city;
41+
// const stateName = place.state;
42+
// const pop = place.population;
43+
44+
const regex = new RegExp(this.value, 'gi');
45+
const placeName = place.city.replace(regex, `<span class="hl">${this.value}</span>`);
46+
const stateName = place.state.replace(regex, `<span class="hl">${this.value}</span>`);
47+
48+
return `
49+
<li>
50+
<span>${placeName}, ${stateName} </span>
51+
<span> ${numberWithCommas(place.population)} </span>
52+
</li>
53+
`
54+
})
55+
56+
return suggestions.innerHTML = html;
57+
58+
59+
60+
}
61+
62+
var searched = document.querySelector('.search');
63+
searched.addEventListener('change', displayItem);
64+
searched.addEventListener('keyup', displayItem);
65+
66+
var suggestions = document.querySelector('.suggestions');
67+
// suggestions.innerHTML = something
68+
2069
</script>
2170
</body>
2271
</html>

0 commit comments

Comments
 (0)