"cascade dropdown list using jquery/php" Answer’s


Lets take an easy example, I'm using this and it works perfectly fine.

This is the country dropdown:

        $countrylist=mysql_query("SELECT * FROM country ORDER BY name ASC");
        echo "<select name='country' id='country' onchange="reload(this.form)" title='Country e:g; United Kingdom,Pakistan'><option value='0'>Select Country</option>";
        echo "<option value='$clist[Name]'>$clist[Name]</option>"."<br/>";
        echo "</select>";

This is the region dropdown:

<select name="region" id="region" ></select>

Now make a seperate file named crlist.js and include it in the page having above code like this:

<script  type="text/javascript" src="crlist.js"> </script>

code for crlist.js:

var request = false;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
request = false;
@end @*/
function fillSelect(country,path) {
var url = path+"crlist.php?country=" + country;
request.open("GET", url, true);
request.onreadystatechange = go;

function go() {
if (request.readyState == 4) {
//if (request.status == 200) {

var response = request.responseText;

var list=document.getElementById("region");
            for (i = list.length - 1; i>=0; i--) {
var records=response.split('|');
for (i=1; i<records.length; i++) {
    var record=records[i].split('*');
    var region=record[0];
    var regionid=record[1];
    var x=document.createElement('option');
    //var y=document.createTextNode(region);

function initCs(path) {

if (!request && typeof XMLHttpRequest != 'undefined') {
request = new XMLHttpRequest();
var country=document.getElementById('country');
    country.onchange=function() {

        if(this.value!="Select") {

            var list=document.getElementById("region");
            for (i = list.length - 1; i>=0; i--) {
        //while (list.childNodes[0]) {


Now make a seperate file named crlist.php.

Code for crlist.php:

require_once 'yourconfigfile.php';

$cname = $_GET['country'];

$query="select ID,Name from city where CountryCode=(select code from country where name='$cname') Order By Name ASC";
$res = mysql_query($query) or die(mysql_error());
while($region = mysql_fetch_array($res)){
    echo "<option value='".$region['Name']."'>".$region['Name']."</option>";

Now add following script on the page having dropdowns:

<script  type="text/javascript" src="crlist.js"> </script>
$(document).ready(function() {



This is my own script, and i've assumed that you have created country and region tables. But you need to tweak the queries and above code according to your db structure.

Hope this helps.

Wednesday, March 31, 2021
answered 10 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :