Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 };
            })
          };
        }
    });

});
like image 266
Vishal Avatar asked Jan 18 '26 03:01

Vishal


1 Answers

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>
like image 79
Zakaria Acharki Avatar answered Jan 20 '26 18:01

Zakaria Acharki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!