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

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"));
        }
    });
});

Exactly like others said, you have to handle the onchange event of country & state select inputs & apply your logic. I have fiddled here for getting states dynamically on selecting a country, you might be able to code the rest yourself - Fiddle

You may also see this Populating Dropdown Based On Other Dropdown Value