Load Values ​​in select2 multiselect

I use select2 instead of the search field.

Here I use to load country values ​​such as

 $("#countries").select2({ multiple: true, tags:["India", "Japan", "Australia","Singapore"], tokenSeparators: [","] }); 

When I click the "Save" button, they are sent to the server correctly, now the question arises: when I want to change the country field after saving to the server, how can I load the saved values ​​in the country field.

This is how I retrieve data from the server

 $.getJSON('/dataprovider?data=fetchCountriesForm', function(opts) { //the opts here contains the json values of the countries. //what code should be written here to load the values in $('#countries).select2(); //user can add some more countries or can remove the previously added countries. } 
+7
source share
2 answers

I just use this link http://ivaynberg.imtqy.com/select2/#event_ext_change and use the trigger function to load the values

 $.getJSON('/dataprovider?data=fetchCountriesForm', function(opts) { parent.parent.parent.showLoader(); if (opts) { $("#countries").val(opts).trigger("change"); } 

This trick loads the value into the select box.

+4
source

Please see the documentation in the Loading Remote Data section.

You will find an example like:

 $("#e6").select2({ placeholder: "Search for a movie", minimumInputLength: 1, ajax: { // instead of writing the function to execute the request we use Select2 convenient helper url: "http://api.rottentomatoes.com/api/public/v1.0/movies.json" // Other stuffs } }); 

You can also do the following:

 $.getJSON('/dataprovider?data=fetchCountriesForm', function(opts){ $("#countries").select2({ data: opts }); }) 

Your JSON data should be in the format shown below:

 [{id:0,text:'enhancement'}, {id:1,text:'bug'}, {id:2,text:'duplicate'}, {id:3,text:'invalid'}, {id:4,text:'wontfix'} ] 
+8
source

All Articles