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.
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.
You need to cascade the .change()
events of the three text boxes such that:
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"));
}
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With