1+ <!DOCTYPE html>
2+ < html >
3+ < head >
4+ < title > </ title >
5+ < link rel ="stylesheet " type ="text/css " href ="myStyle.css ">
6+ </ head >
7+ < body >
8+
9+ < form class ="search-form ">
10+ < input type ="filter " class ="search-filter-box " placeholder ="City or State ">
11+
12+ < ul class ="suggestions ">
13+ < li > Filter for a city</ li >
14+ < li > or a state</ li >
15+ </ ul >
16+
17+ </ form >
18+
19+ < script >
20+
21+ const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json' ;
22+
23+ const cities = [ ] ;
24+
25+ // Returns a array with matched name or state
26+ function findMatches ( wordToMatch , cities ) {
27+ return cities . filter ( place => {
28+ // here we need to figure out if the city or state matches what was searched
29+ const regex = new RegExp ( wordToMatch , 'gi' ) ;
30+ return place . city . match ( regex ) || place . state . match ( regex )
31+ } ) ;
32+ }
33+
34+ // Beautify floats
35+ function numberWithCommas ( x ) {
36+ return x . toString ( ) . replace ( / \B (? = ( \d { 3 } ) + (? ! \d ) ) / g, ',' ) ;
37+ }
38+
39+ function displayMatches ( ) {
40+ displayMatchesWith ( this . value ) ;
41+ }
42+
43+ function displayMatchesWith ( text ) {
44+
45+ const matches = findMatches ( text , cities ) ;
46+
47+ // Generate new html based on the input to serve back to the DOM
48+ const html = matches . map ( place => {
49+
50+ const regex = new RegExp ( text , 'gi' ) ;
51+ const cityName = place . city . replace ( regex , `<span class="hl">${ text } </span>` ) ;
52+ const stateName = place . state . replace ( regex , `<span class="hl">${ text } </span>` ) ;
53+
54+ return `
55+ <li>
56+ <span class="name">${ cityName } , ${ stateName } </span>
57+ <span class="population">${ numberWithCommas ( place . population ) } </span>
58+ </li>
59+ ` ;
60+
61+ } ) . join ( '' ) ;
62+
63+ suggestions . innerHTML = html ;
64+
65+ }
66+
67+ const searchInput = document . querySelector ( '.search-filter-box' ) ;
68+ const suggestions = document . querySelector ( '.suggestions' ) ;
69+ searchInput . addEventListener ( 'change' , displayMatches ) ;
70+ searchInput . addEventListener ( 'keyup' , displayMatches ) ;
71+
72+ fetch ( endpoint )
73+ . then ( blob => blob . json ( ) ) // convert raw data into json
74+ . then ( data => {
75+ cities . push ( ...data ) ;
76+ displayMatchesWith ( '' ) ; // display everything as default
77+ } ) ;
78+
79+ </ script >
80+
81+ </ body >
82+ </ html >
0 commit comments