Keith

Autocomplete Country Filter

by Keith Rowles • 25/03/2023JavaScript

Back view of a coder working in front of a computer

Summary

A simple auto complete tool to filter out world countries. Use country name or abbreviation.

Type a country name into the text input field to display the results.

The results will output into the web page.

You can either use the country name or abbreviation.

eg. au will return Australia.

HTML

<div class="container mt-5">
  <div class="row">
    <div class="col-md-6 m-auto">
      <h3 class="text-center mb-3">
        <i class="fas fa-globe"></i> Country Lookup
      </h3>
      <div class="form-group mb-3">
        <input
          type="text"
          class="form-control form-control-group"
          id="search"
          placeholder="Enter Country Name or Abbreviation"
        />
      </div>
      <div id="match-list"></div>
    </div>
  </div>
</div>

JS

const search = document.getElementById('search');
const matchList = document.getElementById('match-list');

// search the countries json and filter it
const searchCountries = async (searchText) => {
  const res = await fetch('countries.json');
  const countries = await res.json();

  // get matches to current text inputs
  let matches = countries.filter((country) => {
    const regex = new RegExp(`^${searchText}`, 'gi');
    return country.name.match(regex) || country.code.match(regex);
  });

  if (searchText.length === 0) {
    matches = [];
    matchList.innerHTML = '';
  }

  outputHtml(matches);
};

const outputHtml = (matches) => {
  if (matches.length > 0) {
    const html = matches
      .map(
        (match) => `
            <div class="card card-body mb-3">
                <h4>${match.name} (${match.code})</h4>
            </div>
        `
      )
      .join('');

    matchList.innerHTML = html;
  }
};

search.addEventListener('input', () => searchCountries(search.value));

JSON

Here is a snippet of the json file:

[
  { "name": "Afghanistan", "code": "AF" },
  { "name": "Åland Islands", "code": "AX" },
  { "name": "Albania", "code": "AL" },
  { "name": "Algeria", "code": "DZ" }
]

Tech and Tools

  • JavaScript
  • JSON
  • HTML
  • cPanel
  • Filezilla

Demo

I have hosted this demonstration on my own shared web server.

Link to Demo