Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate select2 with JSON after init doesnt work

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)

like image 468
james fray Avatar asked May 28 '15 07:05

james fray


People also ask

How do I create a Select2 dynamically?

HTML. Create a <select class="select2_el" > element to initialize select2 on page load and create <div id="elements" > container to store <select > element on button click using jQuery AJAX.

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

var initial_creditor_id = "3"; $(". creditor_select2"). select2({ ajax: { url: "/admin/api/transactions/creditorlist", dataType: 'json', delay: 250, data: function (params) { return { q: params. term, c_id: initial_creditor_id, page: params.

How do I assign a value to Select2?

New options can be added to a Select2 control programmatically by creating a new Javascript Option object and appending it to the control: var data = { id: 1, text: 'Barn owl' }; var newOption = new Option(data. text, data.id, false, false); $('#mySelect2'). append(newOption).

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


1 Answers

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>
like image 91
Mivaweb Avatar answered Oct 19 '22 22:10

Mivaweb