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...
$.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.
You need to get the value of the "previous" dropdown, and filter out the other ones. Basicly you got two options:
In your code you have to write all handlers when you make a selection, and have to query your JSON objects according to the input parameter and populate your further dropdowns, like you made the country. In that case you have all data on client side in JSON. Usually this kind of data are in a database, so you have to get from the server.
You can make it with JQuery Autocomplete Widget.
First selection you enable only the Country autocomplete.
After the user made the selection you set the state source in javascript (pass the Country parameter to the method, and when the user is typing you populates the value from the server according to the country parameter).
When the user have made the 2. selection you will enable the third autocomplete, and set the input "state" parameter and populate the values according to that in the city autocomplete.
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 - FiddleYou may also see this Populating Dropdown Based On Other Dropdown ValueYou 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.