Skip to content

Commit 6147898

Browse files
author
=
committed
updated suggestions component to show results
1 parent e8ee952 commit 6147898

File tree

1 file changed

+33
-9
lines changed

1 file changed

+33
-9
lines changed

06 - Type Ahead/index-START.html

Lines changed: 33 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -24,21 +24,45 @@
2424
})
2525
.then((data) => {
2626
cities.push(...data);
27-
28-
console.log(findMatches('san', cities));
2927
})
3028
.catch((e) => {
3129
console.log(e);
3230
})
3331

34-
function findMatches(wordToMatch, cities){
35-
return cities.filter((place) => {
32+
function findMatches(wordToMatch, cities){
33+
return cities.filter((place) => {
34+
35+
// g means we will do a global search via the regex and i means case incensitive
36+
const regex = new RegExp(wordToMatch, 'gi');
37+
return place.city.match(regex) || place.state.match(regex);
38+
});
39+
}
40+
41+
42+
function displayMatches(){
43+
const matchArray = findMatches(this.value, cities);
44+
45+
// .join turns array into one big string
46+
const html = matchArray.map((place) => {
47+
return `
48+
<li>
49+
<span class='name'>${place.city}, ${place.state}</span>
50+
<span class='population'>${place.population}</span>
51+
</li>
52+
`;
53+
}).join('');
54+
suggestions.innerHTML = html;
55+
};
56+
57+
const searchInput = document.querySelector('.search');
58+
const suggestions = document.querySelector('.suggestions');
59+
60+
// evertime a word is entered
61+
searchInput.addEventListener('change', displayMatches);
62+
// fire evertime a key is pressed
63+
searchInput.addEventListener('keyup', displayMatches);
64+
3665

37-
// g means we will do a global search via the regex and i means case incensitive
38-
const regex = new RegExp(wordToMatch, 'gi');
39-
return place.city.match(regex) || place.state.match(regex);
40-
});
41-
}
4266
</script>
4367
</body>
4468
</html>

0 commit comments

Comments
 (0)