|
8 | 8 | <body> |
9 | 9 |
|
10 | 10 | <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"> |
13 | 13 | <li>Filter for a city</li> |
14 | 14 | <li>or a state</li> |
15 | 15 | </ul> |
16 | 16 | </form> |
17 | 17 | <script> |
18 | 18 | 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)) |
19 | 23 |
|
| 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) |
20 | 56 | </script> |
21 | 57 | </body> |
22 | 58 | </html> |
0 commit comments