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)
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.
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.
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).
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();
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With