Skip to content

Commit fa27d28

Browse files
committed
06 Fetch JSON, filter matches with regex, display results. Highlight match, format number
1 parent 91bfa39 commit fa27d28

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

06 - Type Ahead/index.html

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<title>Type Ahead 👀</title>
6+
<link rel="stylesheet" href="style.css">
7+
</head>
8+
<body>
9+
10+
<form class="search-form">
11+
<input type="text" class="search" placeholder="City or State">
12+
<ul class="suggestions">
13+
<li>Filter for a city</li>
14+
<li>or a state</li>
15+
</ul>
16+
</form>
17+
<script>
18+
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
19+
const cities = []
20+
fetch(endpoint)
21+
.then(blob => blob.json())
22+
.then(data => cities.push(...data))
23+
24+
function findMatches(wordToMatch, cities) {
25+
const regex = new RegExp(wordToMatch, 'gi')
26+
return cities.filter(place => place.city.match(regex) || place.state.match(regex))
27+
}
28+
29+
function displayMatches(e) {
30+
const matches = findMatches(searchInput.value, cities)
31+
resultHTML = ''
32+
matches.forEach(({rank, city, state}) => {
33+
resultHTML += `<li value="${rank}">${city}, ${state}</li>`
34+
})
35+
searchResult.innerHTML = resultHTML
36+
}
37+
38+
const searchInput = document.querySelector('.search')
39+
const searchResult = document.querySelector('ul.suggestions')
40+
41+
searchInput.addEventListener('keyup', displayMatches)
42+
searchInput.addEventListener('change', displayMatches)
43+
44+
45+
</script>
46+
</body>
47+
</html>

0 commit comments

Comments
 (0)