Select2: how to set data after init?

Erik picture Erik · Mar 16, 2013 · Viewed 53.5k times · Source

I need to set an array of data after initializing select2. So I want to make something like this:

var select = $('#select').select2({});
select.data([
  {id: 1, text: 'value1'},
  {id: 1, text: 'value1'}
]);

But I get the following error:

Option 'data' is not allowed for Select2 when attached to a element.;

My HTML:

<select id="select" class="chzn-select"></select>

What should I use instead of a select element?

I need to set the source of items for search

Answer

PSR picture PSR · Mar 17, 2013

In onload:

$.each(data, function(index, value) {
  $('#selectId').append(
    '<option value="' + data[index].id + '">' + data[index].value1 + '</option>'
  );
});