Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate state and city dropdowns based on country and state using jQuery

I am trying to accomplish dropdowns using JSON. I want 3 dropdowns. First populate the country dropdown (eg: usa, uk etc.,). Now, when the user select USA then states dropdown needs to be populated by using jQuery .change(). Again when user select the state they need to be presented with cities dropdowns.

How can I achieve this? As my JSON file is slightly big I have added it here and tried to populate countries dropdown but unable to generate states and cities drop down...

http://jsfiddle.net/vCFv6/

$.each(myJson.country, function (index, value) {
$("#country").append('<option value="'+value.id+'">'+value.name+'</option>');});

The above code helps me populate just the countries but not others like states and cities. Any help is much appreciated.

Thanks in advance.

like image 502
SpiritOfDragon Avatar asked Jul 01 '13 11:07

SpiritOfDragon


People also ask

How to get state based on country dropdown using jQuery?

Answer: Use the jQuery ajax() method Populating the state or city dropdown based on the value of option selected by the user in the country dropdown is a very common implementation of Ajax feature that you have seen on many websites while filling the registration form.


1 Answers

You need to cascade the .change() events of the three text boxes such that:

  • Changing country:
    • Empties the state and city dropdown
    • Populates the state dropdown (asynchronously)
  • Changing state:
    • Empties the city dropdown
    • Populate the city drop down (asynchronously)

Below is a draft outline which shows how to chain the event handlers. The dropdowns are populated asynchronously so the dependent dropdowns are emptied before AJAX request.

$("#country").change(function () {
    $("#state, #city").find("option:gt(0)").remove();
    $("#state").find("option:first").text("Loading...");
    $.getJSON("/get/states", {
        country_id: $(this).val()
    }, function (json) {
        $("#state").find("option:first").text("");
        for (var i = 0; i < json.length; i++) {
            $("<option/>").attr("value", json[i].id).text(json[i].name).appendTo($("#state"));
        }
    });
});
$("#state").change(function () {
    $("#city").find("option:gt(0)").remove();
    $("#city").find("option:first").text("Loading...");
    $.getJSON("/get/cities", {
        state_id: $(this).val()
    }, function (json) {
        $("#city").find("option:first").text("");
        for (var i = 0; i < json.length; i++) {
            $("<option/>").attr("value", json[i].id).text(json[i].name).appendTo($("#city"));
        }
    });
});
like image 71
Salman A Avatar answered Sep 21 '22 01:09

Salman A