jQuery Dependent DropDown List – Countries and States

Adding Dependent dropdowns will be a very useful feature when there is a dependency between the options of the dropdown fields. For example, if we need to list out the posts based on its category then we can have dependent category-post dropdowns. In this tutorial, we are going create country-state dependent dropdowns. On changing the countries dropdown values, the state dropdown options is loaded dynamically. I use jQuery AJAX to get the dependent options for the state dropdown based on the selected country. In a previous tutorial, we have seen an example with the countries list to filter country name using jQuery autocomplete.

.

View Demo

HTML Dynamic Dependent Dropdown

The following HTML code contains dependent dropdowns for countries and states. Country options are read from the database and shown in the dropdown on page load. Initially, the state dropdown has no options. On changing the country dropdown values, a jQuery function is called to get dependent state options and loaded dynamically.

<div class="frmDronpDown">
	<div class="row">
		<label>Country:</label><br/>
		<select name="country" id="country-list" class="demoInputBox" onChange="getState(this.value);">
		<option value="">Select Country</option>
		<?php
		foreach($results as $country) {
		?>
		<option value="<?php echo $country["id"]; ?>"><?php echo $country["name"]; ?></option>
		<?php
		}
		?>
		</select>
	</div>
	<div class="row">
		<label>State:</label><br/>
		<select name="state" id="state-list" class="demoInputBox">
		<option value="">Select State</option>
		</select>
	</div>
</div>

Getting States using jQuery AJAX

The following jQuery script shows a function to send an AJAX request to PHP to read state list depends on the selected country. This AJAX call is set with the selected country id.

<script>
function getState(val) {
	$.ajax({
	type: "POST",
	url: "get_state.php",
	data:'country_id='+val,
	success: function(data){
		$("#state-list").html(data);
	}
	});
}
</script>

Read State Database using PHP

In PHP, it connects the database to retrieve “states” table values based on the country id passed by jQuery AJAX call. It forms state dropdown options and returns as the AJAX response. This response is inserted to the state dropdown.

<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_POST["country_id"])) {
	$query ="SELECT * FROM states WHERE countryID = '" . $_POST["country_id"] . "'";
	$results = $db_handle->runQuery($query);
?>
	<option value="">Select State</option>
<?php
	foreach($results as $state) {
?>
	<option value="<?php echo $state["id"]; ?>"><?php echo $state["name"]; ?></option>
<?php
	}
}
?>

View DemoDownload

This jQuery code tutorial was published on February 8, 2015.

↑ Back to Top