tags:

views:

676

answers:

3

Hi, I have chain of drop down like Country / state and City. Is there is any way to wait until the drop down population then proceed further? Some time its works properly. Following are code snipit Where Country Drop down always populated but State drop populate base on Country Value and City populate base on State value which from Database. Afterwords i need to set State and City option as Selected In that getOption() populates option base on country state values.

success: function(json){                    
                    var obj = JSON.parse(json);                                         

                    $("#country").val(obj[0].BUSINESS_COUNTRY); // Always in populated state
                    $("#state").addOption(getOption("#state",obj[0].BUSINESS_COUNTRY),false);// This populates base on country value using getOption method                                         
                    $("#city").addOption(getOption("#city",obj[0].BUSINESS_STATE),false);   //This populates base on State value



                    setTimeout(function() {                 
                        $("#state").val(obj[0].BUSINESS_STATE);
                        $("#city").val(obj[0].BUSINESS_CITY);
                    },400); 
                }
A: 

If the selects are chained you'll need to run the ajax on each select's change and then populate the next one in the list. To do that create a generic function that takes the select's type (city, state, or country) and sets the selects below it and bind it to the change event.

Something like this:

<select id="country"></select>
<select id="state"></select>
<select id="city"></select>

$(document).ready(function() {

    populateLists("country");

    $("#country, #city, #state").change(function() {
        populateLists($(this).attr("id"));
    });

    function populateLists(listType) {

        // do your ajax here (should return an array or string with all corresponding values)

        // on success do this:

        var list;

        if(listType == "country") {
            // populate states
            list; = $("#state");
        } else if(listType == "state") {
            // populate cities
            list; = $("#city");
        }

        for(var i = 0; i < returnedArray.length; ++i) {
         list.append("<option value='" + returnedArray[i] + "'>" + returnedArray[i] + "</option>");
        }
    }
});
Ariel
A: 

Are you wanting this to be a synchronous ajax call then? You could set async: false on your $.ajax and move your state and city assignments after the ajax is finished. I'm not sure what else is going on in your method if that's a feasible move for you.

Sometimes synchronous is what we want. jQuery Docs, options section.

neatlysliced
Please don't do this. Use an async request and a callback.
jvenema
A: 

Yashwant Chavan, can you show me your implementation i am after creating cascading dropdownlist.

Abu Hamzah