Skip to content

Commit 2b21f66

Browse files
author
Carlos Filoteo
committed
Add solution for project 05.
1 parent de0d2f7 commit 2b21f66

1 file changed

Lines changed: 34 additions & 3 deletions

File tree

06 - Type Ahead/index-START.html

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,48 @@
66
<link rel="stylesheet" href="style.css">
77
</head>
88
<body>
9-
109
<form class="search-form">
11-
<input type="text" class="search" placeholder="City or State">
12-
<ul class="suggestions">
10+
<label for="search">Search by city or state</label>
11+
<input id="search" type="text" class="search" placeholder="City or State">
12+
<ul id="suggestions" class="suggestions">
1313
<li>Filter for a city</li>
1414
<li>or a state</li>
1515
</ul>
1616
</form>
1717
<script>
1818
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
19+
const cities = [];
20+
const search = document.getElementById('search')
21+
const suggestions = document.getElementById('suggestions')
22+
23+
fetch(endpoint)
24+
.then(res => res.json())
25+
.then(data => cities.push(...data))
26+
27+
search.addEventListener('input', displayMatches)
28+
29+
function findMatches(word, cities) {
30+
const regex = new RegExp(word, 'gi')
31+
return cities.filter(({city, state}) => {
32+
return city.match(regex) || state.match(regex)
33+
});
34+
}
1935

36+
function displayMatches() {
37+
const results = findMatches(this.value, cities)
38+
const hlRegex = new RegExp(this.value, 'gi')
39+
const resultHtml = results.map(({city, state, population}) => {
40+
city = city.replace(hlRegex, `<span class="hl">${this.value}</span>`)
41+
state = state.replace(hlRegex, `<span class="hl">${this.value}</span>`)
42+
return `
43+
<li>
44+
<span class="name">${city}, ${state}</span>
45+
<span class="population">${Number(population).toLocaleString()}</span>
46+
</li>
47+
`
48+
}).join('')
49+
suggestions.innerHTML = resultHtml
50+
}
2051
</script>
2152
</body>
2253
</html>

0 commit comments

Comments
 (0)