it should look something like
$(function(){ // populate the states list from Ajax $.ajax( { url:"/listStates", type:"GET", success:function( data ) { var statesList = data; if ( typeof(data) == "string" ){ statesList = JSON.parse(data); } $.each( statesList, function( index, state ){ $("#state").append($("<option></option>",{value:state.value, text:state.label}); }); }, error:function( result ) { console.log(["error getting states",result]); } }); // register on state list change $("#state").change( function(){ // on change dispatch an AJAX request for cities and populate cities $.ajax({ url : "/listCities", data : {"state": $("#state").val() }, type:'GET', success:function( data ) { var citiesList = data; // assuming list object if ( typeof(data) == "string"){ // but if string citiesList = JSON.parse( data ); } $("#city").empty(); $.each(citiesList, function(index,city){ $("#city").append($("<option></option>", {"value":city.value, "text":city.label})); } }, error:function( result ){ console.log(["error", result]); } }) });
This can get you started however I did not follow lint best practices here.
Walk Through
- I register for a "change" event on select with id state.
- When a change if fired, I invoke an Ajax request to location "/listCities"
- I assume this location is called with a "GET" method
- I pass along the state that is currently selected - so the server will know which cities to list.
- If the Ajax through an error, I log the error to the console.
- If the Ajax was a success, I populate the select with id "city" with options containing values for each city and a label.
I assumed the following things while writing the code
- You have a route GET /listCities that expects a state.
The response from that route is a JSON containing a list of values and labels for each city. Something like this :
[{ value : "AM" , label : "Amsterdam" }, .... ]
The only things you may need to read about for this example are :
If you have any questions, please comment my response, I will be happy to explain/add/modify