How to use HTML5 localstorage with JQuery select2 plugin

Can I use HTML5 localstorage method with jQuery plugin select2

? Right now when I enter data and close the browser / tab, all the data I entered is gone, which is not so optimal as it can be confusing if you don't remember what you entered.

My select2 code looks like this:

$(".select").select2({
minimumInputLength: 1,
multiple: true,
query: function(query){

    $.getJSON( 'url path to remote API', {
      name:query.term, 
      featured:true
     }, function(results){

        var data = {results: []};
        $.each(results.data, function(index, item){
            data.results.push({id: item.artist_id, text: item.name});
        });
        query.callback(data);   

     } );
}
}); 

      

Any help is greatly appreciated

+3


source to share


2 answers


try it: http://jsfiddle.net/7267rkxy/12/

I commented out the code for you for some explanation of what's going on, you can just replace the option data

with a parameter query

and it should still work

PS: I noticed that none of your answered questions were marked "accepted", if someone gives you an answer that you like or what works for you, you should mark your answer "accepted" by checking the box next to the answer




Html

<!-- setting a hard width for example -->
<input type="text" class="select" style="width:200px;" value="" />

      

Js

// set value property to local storage value
$(".select").val(localStorage.s2options);

$(".select").select2({
minimumInputLength: 1,
multiple: true,
data: [{id: 1, text: 'option1'},{id: 2, text: 'option2'},{id: 3, text: 'option3'}], //sample data
initSelection: function (element, callback) {
    // initSelection only fires when there is something in the value property
    callback($.parseJSON(element.val()));
}
}).on('change', function(info){
   // checking if we have anything stored in local storage
   var s2options = localStorage.s2options ? JSON.parse(localStorage.s2options) : [];

   // add / remove options
   if (info.added) {
       s2options.push(info.added);
   } else if (info.removed) {
       s2options = s2options.filter(function(opt) {
           return opt.id != info.removed.id;
       });
   }

    // save selections to local storage
    localStorage.s2options = JSON.stringify(s2options);
});

      

+2


source


In addition to @ bruchowski's answer, the newer version of Select2 has a different way to do it ( initSelection

and query

is still supported for backward compatibility):



You need to create a custom DataAdapter and implement current()

and query()

.

+1


source







All Articles