Create Country & State Dropdown List in Javascript – Countries.js

Category: Text & Input | April 25, 2019
Country & State Dropdown List in Javascript
Author: IshanDemon
Official Page: Go to Website
Last Update:September 14, 2019
License:MIT

This Javascript library helps you to create a country & state dropdown lists which contain the names of all country and state names. You can easily implement a country-state without storing in database.

It’s very simple to add the pre-defined class name and attribute into the dropdown select input box field to make it work.

When a user selects a country, The state dropdown will automatically populate according to the selection of the country name.

Create a Country State Dropdown by using JavaScript

It’s dead simple to add it on your website. You can add it on any kind of website. Whether you have a CMS based site or a static website.

The plugin comes with a single countries.js Javascript file. It contains the country and state by using the variable. Moreover, It included some basic functionality to handle the functionality of populating the values.

Let’s load a Javascript file and add in the before closing the head or before closing body tag at end of the page.

<script src="path/countries.js"></script>

Next, Create the list of for country and state. For this, Simply define the select element (without adding option) and add a unique ID for both country & state.

You can add a label if you want. We did add it for demo purpose.

<label>Select Country (with states):</label>
<select id="country" name ="country"></select>
<label>Select State:</label> 
<select name ="state" id ="state"></select>

Lastly, We need to initialize the Javascript function. All we need to define the first parameter is the ID of country drop-down and the second parameter is the ID of state drop-down.

<script language="javascript">
	populateCountries("country", "state"); 
</script>

Advantages:

By using this plugin, You have a few advantages:

  • No need to save values in the database.
  • No need to use Jquery to avoid conflict.
  • You can manually add/delete and update countries and states.

You May Also Like

2 thoughts on “Create Country & State Dropdown List in Javascript – Countries.js”

  1. Awesome work, thanks a lot for sharing !
    I was just wondering how can we make it an input field instead of a select ? And add an autocomplete to show selection in the existing dropdown ?

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.