jQuery Dependent DropDown List–States and Districts
jQuery Dependent DropDown List–States and Districts
In this tutorial, we are going to see how to change the district dropdown list option based on the selected state name.
For Localhost create a database with name demos and import the SQL file available inside the download package.
View Demo
In this example, we have two dropdowns for listing states and districts. On changing states drop-down values, the corresponding district dropdown values will be loaded dynamically using jQuery AJAX.
HTML Code for state and district dropdown
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<form name="insert" action="" method="post"> <table width="100%" height="117" border="0"> <tr> <th width="27%" height="63" scope="row">Sate :</th> <td width="73%"><select onChange="getdistrict(this.value);" name="state" id="state" class="form-control" > <option value="">Select</option> <?php $query =mysqli_query($con,"SELECT * FROM state"); while($row=mysqli_fetch_array($query)) { ?> <option value="<?php echo $row['StCode'];?>"><?php echo $row['StateName'];?></option> <?php } ?> </select></td> </tr> <tr> <th scope="row">District :</th> <td><select name="district" id="district-list" class="form-control"> <option value="">Select</option> </select></td> </tr> </table> </form> |
Getting States using jQuery AJAX
This script contains a function that will be called on changing state dropdown values. It will send AJAX request to a PHP page to get corresponding district dropdown options.
1 2 3 4 5 6 7 8 9 10 11 12 |
<script> function getdistrict(val) { $.ajax({ type: "POST", url: "get_district.php", data:'state_id='+val, success: function(data){ $("#district-list").html(data); } }); } </script> |
Read State Database using PHP
This PHP code connects the database to retrieve district table values based on the country id passed by jQuery AJAX call.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php require_once("config.php"); if(!empty($_POST["state_id"])) { $query =mysqli_query($con,"SELECT * FROM district WHERE StCode = '" . $_POST["state_id"] . "'"); ?> <option value="">Select District</option> <?php while($row=mysqli_fetch_array($query)) { ?> <option value="<?php echo $row["DistrictName"]; ?>"><?php echo $row["DistrictName"]; ?></option> <?php } } ?> |
For Localhost create a database with name demos and import the SQL file available inside the download package.
View Demo