jQuery Dependent DropDown List – Countries and States

In this tutorial we are going to see how to change states dropdown list option based on the selected country name. In previous tutorial we have seen countries search with jQuery autocomplete.

In this example, we have two dropdown for listing countries and states. On changing countries dorpdown values, the corresponding states dropdown values will be loaded dynamically using jQuery AJAX.

View Demo

dependent-dropdown-list

HTML Dynamic Dependent Dropdown

This code contains HTML code for countries, states dropdown.

<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

This script contains function that will be called on changing country dropdown values. It will send AJAX request to a PHP page to get corresponding states dropdown options.

<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

This PHP code connects database to retrieve states table values based on the country id passed by jQuery AJAX call.

<?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