Skip to content

Commit 68d38c3

Browse files
committed
finish highlighted search of city / state data using fetch
1 parent 33d678d commit 68d38c3

File tree

1 file changed

+38
-2
lines changed

1 file changed

+38
-2
lines changed

06 - Type Ahead/index-START.html

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,51 @@
88
<body>
99

1010
<form class="search-form">
11-
<input type="text" class="search" placeholder="City or State">
12-
<ul class="suggestions">
11+
<input id="searchFormInput" type="text" class="search" placeholder="City or State">
12+
<ul id="suggestionsList", 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+
let places = []
20+
fetch(endpoint)
21+
.then(resp => resp.json())
22+
.then(data => places.push(...data))
1923

24+
function returnMatches(searchTerm, places){
25+
return places
26+
.filter(({city, state} = place) => {
27+
const regex = new RegExp(searchTerm, 'gi')
28+
console.log("city",city)
29+
return city.match(regex) || state.match(regex)
30+
})
31+
}
32+
33+
function highlightedText(text, textToHighlight){
34+
const regex = new RegExp(textToHighlight, 'gi')
35+
return text.replace(regex, (match) => `<span class="hl">${match}</span>`)
36+
}
37+
38+
function displayMatchingData(){
39+
const matches = returnMatches(this.value, places)
40+
const html = matches.map(({city, state} = match) => {
41+
const cityName = highlightedText(city, this.value)
42+
const stateName = highlightedText(state, this.value)
43+
return `
44+
<li>
45+
<span class="name">${cityName}, ${stateName}</span>
46+
</li>`
47+
}).join("")
48+
const suggestionsList = window.document.getElementById("suggestionsList")
49+
suggestionsList.innerHTML = html
50+
}
51+
52+
const input = window.document.getElementById("searchFormInput")
53+
input.addEventListener('change', displayMatchingData)
54+
input.addEventListener('keyup', displayMatchingData)
55+
// .then(data => data)
2056
</script>
2157
</body>
2258
</html>

0 commit comments

Comments
 (0)