|
6 | 6 | <link rel="stylesheet" href="style.css"> |
7 | 7 | </head> |
8 | 8 | <body> |
9 | | - |
10 | 9 | <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"> |
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 | +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 | +} |
19 | 35 |
|
| 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 | +} |
20 | 51 | </script> |
21 | 52 | </body> |
22 | 53 | </html> |
0 commit comments