|
15 | 15 | </ul>
|
16 | 16 | </form>
|
17 | 17 | <script>
|
18 |
| -const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json'; |
| 18 | + const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json'; |
| 19 | + const cities = []; |
| 20 | + const data = fetch(endpoint).then(result => result.json()).then(json => cities.push(...json)); |
19 | 21 |
|
| 22 | + function findMatches(wordToMatch, cities) { |
| 23 | + return cities.filter(obj => { |
| 24 | + // here we need to figure out if the city or state matches what was searched |
| 25 | + // g is for global, i for in insensitive |
| 26 | + const regex = new RegExp(wordToMatch, 'gi') |
| 27 | + return obj.city.match(regex) || obj.state.match(regex) |
| 28 | + }) |
| 29 | + } |
| 30 | + |
| 31 | + function displayMatches() { |
| 32 | + const matchArray = findMatches(this.value, cities) |
| 33 | + const html = matchArray.map(obj => { |
| 34 | + const regex = new RegExp(this.value, 'gi') |
| 35 | + const cityName = obj.city.replace(regex, |
| 36 | + `<span class="hl">${this.value}</span>`) |
| 37 | + const stateName = obj.state.replace(regex, |
| 38 | + `<span class="hl">${this.value}</span>`) |
| 39 | + return ` |
| 40 | + <li> |
| 41 | + <span class="name">${cityName} ${stateName}</span> |
| 42 | + <span class="population">${obj.population}</span> |
| 43 | + </li> |
| 44 | + ` |
| 45 | + }).join(''); |
| 46 | + suggestions.innerHTML = html; |
| 47 | + } |
| 48 | + |
| 49 | + const searchInput = document.querySelector('.search'); |
| 50 | + const suggestions = document.querySelector('.suggestions'); |
| 51 | + |
| 52 | + searchInput.addEventListener('change', displayMatches) |
| 53 | + searchInput.addEventListener('keyup', displayMatches) |
20 | 54 | </script>
|
21 | 55 | </body>
|
22 | 56 | </html>
|
0 commit comments