Vishal Vishal - 4 months ago 24
HTML Question

How to pass data to select2 version > 4.0

I am trying to use

select2
for the first time.

I would like to have my data from a static array. Can you please help me?

Here is my code:

$(document).ready(function() {

var names = [{"id":"1","name":"Adair,James"}
, {"id":"2","name":"Anderson,Peter"}
, {"id":"3","name":"Armstrong,Ryan"}];

$("#e10_2").select2({
processResults: function(){
return {
results: $.map(names, function(obj) {
return { id: obj.id, text: obj.name };
})
};
}
});

});

Answer

You could use data option to pass an array to the select2 as :

$("#e10_2").select2({ data: names });

If you don't have text attribute adapt your array check the part of documentation made for this purpose The id and text properties are strictly enforced, e.g :

$(function () {
    var names = [{"id":"1","name":"Adair James"}
                 , {"id":"2","name":"Anderson Peter"}
                 , {"id":"3","name":"Armstrong Ryan"}];

    var data = $.map(names, function (obj) {
      obj.id = obj.id;
      obj.text = obj.name;

      return obj;
    });

    $("select").select2({width: '100%',data: data});
});

Hope this helps.

    $(function () {
        var names = [{"id":"1","name":"Adair James"}
                     , {"id":"2","name":"Anderson Peter"}
                     , {"id":"3","name":"Armstrong Ryan"}];

        var data = $.map(names, function (obj) {
          obj.id = obj.id;
          obj.text = obj.name;

          return obj;
        });

        $("select").select2({width: '100%',data: data});
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://select2.github.io/dist/js/select2.full.js"></script>
<link href="https://select2.github.io/dist/css/select2.min.css" rel="stylesheet"/>
<select></select>