Populate select2 with JSON after init doesnt work

james fray picture james fray · May 28, 2015 · Viewed 15.3k times · Source

I'm trying to populate a select2 element with a JSON array; but I can't get it.

I have the next array:

data = [{"id":"Foo","text":"Foo"},{"id":"Bar","text":"Bar"}]

And I initialize select2 as follow:

$("#selectElement").select2();

I use the next code to populate:

$('#selectElement').select2('data', data, true);

But doesnt work and I dont know why. Someone can help me?

EDIT: I need to populate after the init of select2 (I receive JSON from AJAX)

My intention is populate the select2 of my question with the JSON of the AJAX search of other select2.

All works well except the populate (I get this JSON well in the formatSelectiom method of the first but i dont know that can i do to populate the second select2 with this)

Answer

Mivaweb picture Mivaweb · May 28, 2015

I see some differences between your code and the one from select2

Your data:

var data = [{"id":"Foo","text":"Foo"},{"id":"Bar","text":"Bar"}];

Should be:

var data = [{id:"Foo", text:"Foo"},{id:"Bar", text:"Bar"}]

Your population code:

$('#selectElement').select2('data', data, true);

Should be:

$('#selectElement').select2({data: data});

Example from Select2

var data = [
      { id: 0, text: 'enhancement' }, 
      { id: 1, text: 'bug' }, 
      { id: 2, text: 'duplicate' }, 
      { id: 3, text: 'invalid' }, 
      { id: 4, text: 'wontfix' }
];

$(".js-example-data-array").select2({
  data: data
});

<select class="js-example-data-array"></select>