Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select2: how to set data after init?

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

like image 758
Erik Avatar asked Mar 16 '13 20:03

Erik


People also ask

How can I set the initial value of Select2 when using Ajax?

trigger('change'); // append the option and update Select2 $. ajax({ // make the request for the selected data object type: 'GET', url: '/api/for/single/creditor/' + initial_creditor_id, dataType: 'json' }). then(function (data) { // Here we should have the data object $option. text(data.

How do I make Select2 empty?

In order to clear the selection of those values which are selected using a Select2 drop down,we can use the empty() function. The dropdown can be reset using Jquery. $("#select2_example"). empty();

How do I trigger Select2?

trigger('change'); // manually trigger the `select2:select` event studentSelect. trigger({ type: 'select2:select', params: { data: data } }); }); Notice that we manually trigger the select2:select event and pass along the entire data object.


1 Answers

In onload:

$.each(data, function(index, value) {   $('#selectId').append(     '<option value="' + data[index].id + '">' + data[index].value1 + '</option>'   ); }); 
like image 103
PSR Avatar answered Oct 06 '22 01:10

PSR