Skip to content

Commit fe63da9

Browse files
committed
Added Ajax Type Ahead (wesbos#6)
1 parent ecac3dd commit fe63da9

File tree

1 file changed

+41
-4
lines changed

1 file changed

+41
-4
lines changed

06 - Type Ahead/index-START.html

Lines changed: 41 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,46 @@
1414
<li>or a state</li>
1515
</ul>
1616
</form>
17-
<script>
18-
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
17+
<script>
18+
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
1919

20-
</script>
21-
</body>
20+
const cities = [];
21+
fetch(endpoint)
22+
.then(res => res.json())
23+
.then(data => cities.push(...data));
24+
25+
function findMatches(wordToMatch, cities) {
26+
const regex = new RegExp(wordToMatch, 'gi');
27+
return cities.filter(p => p.city.match(regex) || p.state.match(regex));
28+
}
29+
30+
function numberWithCommas(number){
31+
return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
32+
}
33+
34+
function displayMatches(){
35+
const matches = findMatches(this.value, cities);
36+
const html = matches.map(p => {
37+
const regex = new RegExp(this.value, 'gi');
38+
const city = p.city.replace(regex, `<span class="hl">${this.value}</span>`);
39+
const state = p.state.replace(regex, `<span class="hl">${this.value}</span>`);
40+
const population = numberWithCommas(p.population);
41+
42+
return `
43+
<li>
44+
<span class="name">${city}, ${state}</span>
45+
<span class="population">${population}</span>
46+
</li>
47+
`;
48+
}).join('');
49+
50+
suggestions.innerHTML = html;
51+
}
52+
53+
const suggestions = document.querySelector('.suggestions');
54+
const searchInput = document.querySelector('.search');
55+
searchInput.addEventListener('change', displayMatches);
56+
searchInput.addEventListener('keyup', displayMatches);
57+
</script>
58+
</body>
2259
</html>

0 commit comments

Comments
 (0)