Auto Complete Country Application With Javascript & JSON

Introduction

Today we are going to make an autocomplete application that displays the capital and country code of different countries around the world. To do this, we are going to be making use of a json file that contains all the data that we need.

Here is a working example of our project

So, there will be no external API, just an updated json file I created containing what I believe to be all the countries in the world.

If you find out perhaps, that your country isn’t included, feel free to make a pull request as I’ll be putting the link to the Github repo at the end of the tutorial.

Requirements

  • Basic knowledge of Html.
  • Basic knowledge of CSS.
  • Basic knowledge of JSON
  • Basic knowledge of javascript.

We are going to need just three steps to complete this application.

Step One

In this step, we will create the design of the application. We will be making use of Materialize CSS. It is a modern responsive front-end framework based on material design.

We will also be making use of Material icon.

All you need to do is create an index.html file and a style.css file.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" />
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" />

  <link rel="stylesheet" href="css/style.css" />
  <title>Countrypedia</title>
</head>

<body>
  <div class="row container">
    <div class="input-field col s6">
      <h5 class="center-align">
        <i class="small material-icons">flag</i>Select A Country
      </h5>
      <input placeholder="e.g Nigeria" id="search" type="text" class="validate" />
    </div>
  </div>
  <div id="countryList"></div>
  <script src="script.js"></script>
</body>

</html>

index.html hosted with ❤ by GitHub

From the index.html file, we can see that the CDN for both Materialize CSS and material icon can be found in the head tag. This enables us to be able to use their classes in our HTML.

body {
  background-color: white;
  padding: 0 0 0 20%;
  margin: 5%;
}
#countryList {
  width: 70%;
  padding-left: 11%;
}

style.css hosted with ❤ by GitHub

All we did in the css was to centralise the entire body of our input form. With that, if we save and load our file in the browser we should have something like this below:

Step Two

Here we create the data we are going to interact within JSON (JavaScript Object Notation) format. JSONis a lightweight data-interchange format. It is easy for humans to read and write.

Create a folder called data, inside this folder create a file called countries.json. This is where our data will be stored injson format

With json, it is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition – December 1999.

You can find the entire country data in json format from this Link

Like I said earlier if you can’t find your country or a country you know on the list, feel free to make a pull request.

Step Three

This is our final step in the creation of this application. This is where we will be making use of javascript to make the app interactive.

We will make use of the fetch api to get data from the json file in the application using async/await.

//Get Countries From Json File
const searchcountry = async searchBox => {
  const res = await fetch('../data/countries.json');
  const countries = await res.json();
  
  //Get & Filter Through Entered Data
  let fits = countries.filter(country => {
    const regex = new RegExp(`^${searchBox}`, 'gi');
    return country.name.match(regex) || country.abbr.match(regex);
  });
  
  //Clears Data If Search Input Field Is Empty
  if (searchBox.length === 0) {
    fits = [];
    countryList.innerHTML = '';
  }
  outputHtml(fits);
};

script.js hosted with ❤ by GitHub

The above code shows that, after getting the countries from the json file, we used a high order array function called filter() to filter through the entire array of countries in our data.

We then created a regular expression that returns an array that fits the data entered in the input field. With this, you can only search for a country by either it’s name or abbr(abbreviation).

Display Result In Html

There are various ways we can display our data in HTML. We could make use of a for loop, the jQuery.each() function or we could use a high order array called .map().

The .map() makes us simplify our code, so that’s what we will be using. The .map() basically takes in two arguments. A callback and an optional context

In our case, we will be returning an array of html. Our array of Html strings contains classes of materialize CSS for additional styling. We then call the .join() method to join all the Html elements together into a string.

// Display result in HTML
const outputHtml = fits => {
  if (fits.length > 0) {
    const html = fits
      .map(
        fit => `
     <div class="row">
     <div class="col s12">
       <div class="card  grey darken-4 darken-1">
         <div class="card-content white-text">
           <h4 class="card-title m1">${fit.name} (${
          fit.abbr
        })<span class="blue-text m-4"> ${fit.capital}</span></h4>
        <div class="card-action">
        <a>Country Code :</a>
        <a>${fit.phoneCode}</a>
      </div>
         </div>
       </div>
     </div>
   </div>
     `).join('');
  }
};

script.js hosted with ❤ by GitHub

Finally for our app to work, we get the id's of our Html elements, set them as
Html and also add an EventListener to get the values entered in the input field.

document.getElementById('countryList').innerHTML = html;
 }
};
document.getElementById('search').addEventListener('input', () => searchcountry(search.value));

script.js hosted with ❤ by GitHub

Conclusion

With this our simple application is complete and we can search for any country around the globe, alongside their capital and country code.

The link to the entire code can be found here

To get more free content on web development, subscribe to my newsletter:
here

2 thoughts on “Auto Complete Country Application With Javascript & JSON”

  1. Amazing stuff.
    What do you think about wrapping the functions in a try-catch block? Async await can behave weirdly sometimes, maybe you could catch some ofn those weirdness with that. Thanks for putting out this amazing content.

    1+

Leave a Comment

Your email address will not be published.