country state city drop down list using JavaScript

Question: How to populate country state city drop down list using JavaScript? In a simple web application, it may have many requirements around the populate dropdown component. For demo with example, it needs to show populate Cascading A DropDownList with group options. In some supported country state city dropdown api web applications, it needs dependent dropdowns lists with multi-select.

List of all Google Adsense, VueJS, AngularJS, PHP, Laravel Examples.

There are lots of the useful solutions on the web app to sort out those needs. This tutorial provides a custom step by step understands for the json data dependency between a country-state-city HTML inputs form. I have done this before for country-state dropdowns list.

Solution: Using the jQuery ajax() method

Populating the country state city drop down list using JavaScript via on the value of option selected by the people in the country dropdown is a individual Integration of jQuery Ajax component that you have seen on many static or Dynamic Webpages while fill-up the sign up form. You can do this simply through the jQuery Ajax Function along with the little useful of any most popular server side scripting language and frameworks like ASP.NET, PHP, Node. js, Java, Ruby, Perl and Python.

Let’s take a look at the bellow example to know step by step how it fundamentally works:

Dependent Dropdown HTML

It state drop down list in html source code is to show the country state city dependent dropdowns list to the people.

It includes PHP script to load the initial main options for the country dropdown lists. The PHP script DB connects the database Table as well as get the country result in an array format.

Each dropdown lists field’s on change event call on jQuery functions to get the dependent data. The jQuery functions HTTP requests PHP for the dependent JSON data using country drop down list javascript ajax.

This HTML source code has the dependent dropdown lists as a target container. In this HTML target, the AJAX response loads the dependent JSON data dynamically.

In a Old how to get country list in javascript?, we have seen how to show dependent dropdown options with multi-select. It increases the search basis and gets more JSON data for the select box options.

country state city drop down list using ajax in JavaScript Example

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Populate City Dropdown Based on Country Selected - www.pakainfo.com</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function(){
    $("select.country").change(function(){
        var selectedCountry = $(".country option:selected").val();
        $.ajax({
            type: "POST",
            url: "/admin/api/php/do-ajax-request-call.php",
            data: { country : selectedCountry } 
        }).done(function(data){
            $("#response").html(data);
        });
    });
});
</script>
</head>
<body>
<form>
    <table>
        <tr>
            <td>
                <label>Select Your Country:</label>
                <select class="country">
                    <option>Select</option>
                    <option value="usa">United States</option>
                    <option value="india">India</option>
                    <option value="uk">United Kingdom</option>
                </select>
            </td>
            <td id="response">
                <!--Output will be inserted here-->
            </td>
        </tr>
    </table>
</form>
</body> 
</html>

The jQuery script above send the value of option selected in the country dropdown lists to the server. The “do-ajax-request-call.php” file on the server side then process the request, if the request completed or succeeds the jQuery script receives the returned JSON data and makes the city dropdown list.

Country, State, City – Dropdown list

The PHP code inside the “do-ajax-request-call.php” PHP file will look something like this: Country-State-City Example: Cascading jQuery AJAX Dependent Dropdown in PHP

<?php
if(isset($_POST["country"])){
    $country = $_POST["country"];
     
    $countryArr = array(
                    "usa" => array("New Yourk", "Los Angeles", "California"),
                    "india" => array("Gujrat", "Bombay", "Maharastra"),
                    "uk" => array("London", "Manchester", "Liverpool")
                );
     
    if($country !== 'Select'){
        echo "<label>Select Your City:</label>";
        echo "<select>";
        foreach($countryArr[$country] as $value){
            echo "<option>". $value . "</option>";
        }
        echo "</select>";
    } 
}
?>

We have made a simple PHP array to save or update country as well as city records for demo purpose. However, in real world scenario you need to save or update these records in database. Please check out the PHP with MySQL tutorial section to learn about inserting as well as retrieving records from database as well as country, state city drop down list using angular2.

how to bind country state city in jquery?

The dynamic Insert, Update Delete dependent select box is used to auto-populate the dependent JSON data in the dropdown list. Bases on the drop-down selection, the dependent JSON data are retrieved from the database and show in the next select box. Generally, the dynamic Insert, Update Delete dependent select box is used to Integration country state city dropdown lists functionality. Using Ajax & PHP, you can easily Integration dynamic Insert, Update Delete dependent dropdown without page refresh.

Dynamic dependent dropdown is very helpful to get a dynamic Insert, Update Delete relative JSON data from the database and listed in the multiple custom select boxes. In this tutorial, we will show you how to Integration relative dropdown lists of country state city using jQuery, Ajax, PHP, as well as MySQL. This means that the state is related to the country and the city is related to the state. Based on changing of country & state, specific state & city is received from the database without reloading the web page using jQuery, Ajax, PHP, with MySQL.

The example code initially shows all countries in the country dropdown lists. When a country is pick, the specific states will be received from the MySQL database as well as view in the state dropdown lists. Alike when a state is pick, the specific cities will be received from the MySQL database as well as view in the city dropdown lists.

Show city list as per country as well as state select in dropdown lists default select box Javascript. Cascading dropdown list of Country/State/City/Zip

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>how to get country list in javascript - www.pakainfo.com</title>
<script>
var stateObject = {
"India": { "Gujrat": ["Surat", "Rajkot"],
"Kerala": ["Kozhikode", "Malappuram"],
"Goa": ["East Goa 1", "west Goa 2"],
},
"Australia": {
"South Australia": ["Adelaide", "Whyalla"],
"Victoria": ["Bendigo", "Melton"]
}, "Canada": {
"Alberta": ["Edmonton", "Beaumont"],
"Columbia": ["Anza", "Campamento"]
},
}
window.onload = function () {
	var selectCountyList = document.getElementById("selectCountyList"),
	selectStateList = document.getElementById("selectStateList"),
	selectCityList = document.getElementById("selectCityList");
	for (var country in stateObject) {
		selectCountyList.options[selectCountyList.options.length] = new Option(country, country);
	}
	selectCountyList.onchange = function () {
		selectStateList.length = 1; 
		selectCityList.length = 1; 
		if (this.selectedIndex < 1) return; 
		for (var state in stateObject[this.value]) {
			selectStateList.options[selectStateList.options.length] = new Option(state, state);
		}
	}
	selectCountyList.onchange();
	selectStateList.onchange = function () {
		selectCityList.length = 1; 
		if (this.selectedIndex < 1) return; 
		var city = stateObject[selectCountyList.value][this.value];
		for (var i = 0; i < city.length; i++) {
			selectCityList.options[selectCityList.options.length] = new Option(city[i], city[i]);
		}
	}
}
</script>
</head>
<body>
<form name="bookMyHome" id="bookMyHome">
Choose Your Country: <select name="state" id="selectCountyList" size="1">
<option value="" selected="selected">Select Your Country</option>
</select>
<br>
<br>
Choose Your State: <select name="countrya" id="selectStateList" size="1">
<option value="" selected="selected">Please Select Your Country</option>
</select>
<br>
<br>
Choose Your City: <select name="city" id="selectCityList" size="1">
<option value="" selected="selected">Please Select Your State</option>
</select><br>
<input type="submit">
</form>
</body>
</html>

Conclusion

The dynamic dependent select boxes are a very useful HTML Form element when you want to accede the people to choose values from the multiple dropdown list. In the example code, we have shown the dynamic dependent select boxes for country state city dropdown in PHP. You can easily extend the dynamic dependent select boxes functionality as well as Integration jQuery Ajax country state city dropdown with PHP and MySQLi. If you have a lots of the number of data, use the JSON data type in jQuery Ajax and PHP for a light response.

Web Programming Tutorials Example with Demo

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about country state city drop down list using JavaScript.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.


Related FAQ

Here are some more FAQ related to this Article:

  1.   ASP.NET AJAX partial postback in UpdatePanel control
  2.   How to export mysql data to pdf using php with demo?
  3.   Group By with Multiple Columns using Laravel Collection
  4.   country drop down list - All Country State City
  5.   Create Dynamic Web Pages using PHP-MYSQL
  6.   How to bind to checkbox change/click event with Angular?
  7.   jQuery AJAX Submit form serialize PHP MySQLi
  8.   Concept of Encapsulation in PHP OOP Example
  9.   how to get last inserted id in laravel 6?
  10.   PHP Stripe api Send Accept Payment Integration

Leave a Reply

Your email address will not be published. Required fields are marked *