javascript - Chaining multiple Select2 together -


trying make 2 chained auto populating select fields using select2 plugin first select contains countries names(static select) , second shows states of country selected first select code is

<select id="country" name="country" size="1" class=" form-control"> <option></option> <option value="1">usa</option> <option value="2">untied kingdom</option> <option value="3">france</option> etc........ </select> <select id="states" name="states" size="1" class="form-control"> <option></option> </select> 

the javascript code

$(document).ready(function() {     $('#country').select2({         placeholder: 'select country',         allowclear: true     });     $('#state').select2({         placeholder: 'select state',         allowclear: true     });     $('#country').change(function() {             var selectedcountries = $('#countryoption:selected').val();             var selectedcountries = 'id='+ selectedcountries;             $.ajax({                 type: 'post',                 url: 'http://localhost/codeigniter/countries/get_state/',                 datatype: 'html',                 data: selectedcountries,                 }).done( function( data ) {                        data = $.map(data, function(item) {                             return { id: item.id, text: item.name };                          });                         $('#state').select2({                             data: data                         });                 }             })     }); }); 

the returened results in json

{"id":"1","text":"chigaco"}{"id":"4","text":"albama"}{"id":"2","text":"tulsa"} etc........... 

i searched lot example me nothing working right need show states of country chosen in first select , pass second select known i'm using select2 v4.0 , jquery v2

a select2 can chained in same way standard <select> can chained. means when value of first select chained, second select reset (generally placeholder) , options change well.

you have 2 options how can done select2:

  1. pre-load options second <select> when value changes, , let select2 handle searching locally. similar how trying it, may suffer issues when there large number of options can selected in second <select>.

    in case, there shouldn't thousands of "states" (for whatever degree of state) within country, local searching shouldn't of issue.

  2. use select2's ajax functionality , pass in different parameter url use based on value of first <select>. requires have dynamic endpoint can handle retrieving items second select as filtering them when searching, it's not feasible.

    if have endpoint supports filtering, more responsive option user doesn't have wait options retrieved before can select option second <select>.

what option choose largely depends on have set up, size of data set working (select2 not handle thousands of options), , user experience want provide.

the code first option similar to

$("#first").select2({   placeholder: 'select number range' });  $("#second").select2({   placeholder: 'select number' });  $("#first").on("change", function () {   $("#second option[value]").remove();    var newoptions = []; // result of json request    $("#second").append(newoptions).val("").trigger("change"); }); 

and can tested @ following jsbin, using ranges of numbers instead of countries , states: http://jsbin.com/wigalivapi/1/edit?html,output

note while this similar code using, there few small difference have caught you.

  1. you setting datatype: "html" when expecting datatype: "json". returning json in response, not html.

  2. you not clearing <select> before call .select2({data:[]}) second time. select2 doesn't automatically remove <option> tags generates data, need on own.

  3. when change value of <select>, never tell select2 it. need re-trigger change event on second <select> after change it.

  4. the json provide in question not appear valid. i'm not sure if because giving example, check json response jsonlint ensure valid.

the code second option similar to

$("#first").select2({   placeholder: 'select number range' });  $("#second").select2({   placeholder: 'select number',   ajax: {     url: http://localhost/codeigniter/countries/get_state/',     type: 'post',     data: function (params) {       return {         id: $("#first").val(),         search: params.term       }     }   } }); 

and can tested @ following jsbin, mocks response using range of numbers (similar other example): http://jsbin.com/gihusohepe/1/edit?html,output


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -