showing results for - "live search using fetch api"
Valeria
12 Oct 2018
1const search_input = document.getElementById('search');
2const results = document.getElementById('results');
3
4let search_term = '';
5let countries;
6
7const fetchCountries = async () => {
8    countries = await fetch(
9        'https://restcountries.eu/rest/v2/all?fields=name;population;flag'
10    ).then(res => res.json());
11};
12
13const showCountries = async () => {
14    results.innerHTML = '';
15
16    await fetchCountries();
17
18    const ul = document.createElement('ul');
19    ul.classList.add('countries');
20
21    countries
22        .filter(country =>
23            country.name.toLowerCase().includes(search_term.toLowerCase())
24        )
25        .forEach(country => {
26            const li = document.createElement('li');
27            li.classList.add('country-item');
28
29            const country_flag = document.createElement('img');
30            country_flag.src = country.flag;
31            country_flag.classList.add('country-flag');
32
33            const country_name = document.createElement('h3');
34            country_name.innerText = country.name;
35            country_name.classList.add('country-name');
36
37            const country_info = document.createElement('div');
38            country_info.classList.add('country-info');
39
40            const country_population = document.createElement('h2');
41            country_population.innerText = numberWithCommas(country.population);
42            country_population.classList.add('country-population');
43
44            const country_popupation_text = document.createElement('h5');
45            country_popupation_text.innerText = 'Population';
46            country_popupation_text.classList.add('country-population-text');
47
48            country_info.appendChild(country_population);
49            country_info.appendChild(country_popupation_text);
50
51            li.appendChild(country_flag);
52            li.appendChild(country_name);
53            li.appendChild(country_info);
54
55            ul.appendChild(li);
56        });
57
58    results.appendChild(ul);
59};
60
61showCountries();
62
63search_input.addEventListener('input', e => {
64    search_term = e.target.value;
65    showCountries();
66});
67
68// From StackOverflow https://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript
69function numberWithCommas(x) {
70    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
71}