jQuery <select> Changes Another <select>

本秂侑毒 提交于 2019-12-10 22:06:58

问题


I am using trying to use jQuery .change() to create two <select> elements whereby the first <select id="state"> is for generating a list of states and the second <select id="city"> is to generate a list of cities.

The values of states and cities will not be hard-coded but generated from values pass from web services.

The list of options to be generated is supposed to work like this: if user selects state from <select id="state"> the selected value will be pass to a web service to retrieve the list to generate the <select id="city"> for cities.

I'm really not sure how to implement this. Can anyone please advise me?


回答1:


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 :

  • JQuery Ajax Calls
  • Best Practice To Populate A List With JQuery

If you have any questions, please comment my response, I will be happy to explain/add/modify




回答2:


You have to follow some steps achieving this:

  • first when page load populate the first country list via ajax (my assumption)
  • then create a .change() event with the country list
  • This will send a request and returns the states list response as per selected country.

you can try test it this way:

$(function(){
   $.ajax({
      url:your url,
      type: 'post',
      dataType: 'json', // or your choice of returned data
      success: function(data){
          $.each(data, function(i, v){
             $('<option value="'+v.name+'">'+v.text+'</option>').appendTo('#country');
          });
      }
   });

   $('#country').change(function(){
       $.ajax({
         url:your url,
         type: 'post',
         dataType: 'json', // or your choice of returned data
         success: function(states){
             $.each(states, function(i, stt){
                $('<option value="'+stt.name+'">'+stt.text+'</option>').appendTo('#states');
             });
         }
      });
      $('#states').empty();
   });

});



回答3:


Pretty simple - all you'll have to do is have the two dropdowns, one with the full lists of states and the second (empty) city list will contain only one blank disabled option.

As soon as your states dropdown triggers a change event, you extract the state data and send it via an AJAX call to your server or some web service which will return a list of cities in that state.

You'll then populate the second dropdown with the returned city values.



来源:https://stackoverflow.com/questions/14661508/jquery-select-changes-another-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!