DEV Community

Cover image for Auto Complete Country Application With Javascript & JSON
deji adesoga
deji adesoga

Posted on • Edited on

17 7

Auto Complete Country Application With Javascript & JSON

The more I study, the more insatiable do I feel my genius for it to be.
-Ada Lovelace

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>
view raw 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%;
}
view raw 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:

Alt text of image

Step Two

Here we create the data we are going to interact with in 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 were 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 were 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);
};
view raw script.js hosted with ❤ by GitHub

From The above code, after getting the countries from the json file, we used an 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 an 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('');
}
};
view raw 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));
view raw 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

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (7)

Collapse
 
amedalen profile image
Aj

Really inspiring thank you so much, I got really inspired and decided to create a country's capital finder just displaying the capital of any country in python and run on Flask.

dev.to/amedalen/any-countrys-capit...

Once again thank you for this wonderful post.

Collapse
 
nelsoneric profile image
Nelson

Really interesting

Collapse
 
desoga profile image
deji adesoga

Thanks Nelson.

Collapse
 
jasimur profile image
Jasim Uddin

I clone your project from github,, when i opening the html file with browser and search for a country that not working,,, I mean no country and country code did't showing in the display...

Collapse
 
desoga profile image
deji adesoga

Which code editor are you using? If you're using visual studio code, try to open it with livesever. If it's not opened on a server, it will not work.

Collapse
 
jasimur profile image
Jasim Uddin

After clone this project from github, how to run this project...??

Some comments may only be visible to logged-in visitors. Sign in to view all comments.