Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit f00fecd

Browse files
committed
finished ajax
1 parent 79a97c1 commit f00fecd

File tree

1 file changed

+35
-1
lines changed

1 file changed

+35
-1
lines changed

06 - Type Ahead/index-START.html

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,42 @@
1515
</ul>
1616
</form>
1717
<script>
18-
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
18+
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
19+
const cities = [];
20+
const data = fetch(endpoint).then(result => result.json()).then(json => cities.push(...json));
1921

22+
function findMatches(wordToMatch, cities) {
23+
return cities.filter(obj => {
24+
// here we need to figure out if the city or state matches what was searched
25+
// g is for global, i for in insensitive
26+
const regex = new RegExp(wordToMatch, 'gi')
27+
return obj.city.match(regex) || obj.state.match(regex)
28+
})
29+
}
30+
31+
function displayMatches() {
32+
const matchArray = findMatches(this.value, cities)
33+
const html = matchArray.map(obj => {
34+
const regex = new RegExp(this.value, 'gi')
35+
const cityName = obj.city.replace(regex,
36+
`<span class="hl">${this.value}</span>`)
37+
const stateName = obj.state.replace(regex,
38+
`<span class="hl">${this.value}</span>`)
39+
return `
40+
<li>
41+
<span class="name">${cityName} ${stateName}</span>
42+
<span class="population">${obj.population}</span>
43+
</li>
44+
`
45+
}).join('');
46+
suggestions.innerHTML = html;
47+
}
48+
49+
const searchInput = document.querySelector('.search');
50+
const suggestions = document.querySelector('.suggestions');
51+
52+
searchInput.addEventListener('change', displayMatches)
53+
searchInput.addEventListener('keyup', displayMatches)
2054
</script>
2155
</body>
2256
</html>

0 commit comments

Comments
 (0)