I'm giving following data input to select2
data = [{ "id": "all", "text": "All", "children": [{ "id": "item1", "text": "item1" }, { "id": "item2", "text": "item2" }] }];
and I'm initialising select2 as:
$(parent).select2({"data":data});
Now to select the value "item1", I did
$(parent).select2("val",["item1"]);
However instead of value "item1" value "all" is getting selected. How to select value item1?
$("#programid"). select2({ placeholder: "Select a Program", allowClear: true, minimumInputLength: 3, ajax: { url: "ajax.
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).
var data = []; // Programatically-generated options array with > 5 options var placeholder = "select"; $(". mySelect"). select2({ data: data, placeholder: placeholder, allowClear: false, minimumResultsForSearch: 5});
To set the selected value using select2
you should use:
$(parent).val("item1").trigger("change");
From the release notes:
You should directly call .val on the underlying element instead. If you needed the second parameter (triggerChange), you should also call .trigger("change") on the element.
$("select").val("1"); // instead of $("select").select2("val", "1");
JSFiddle where item1 is selected.
JS:
var data = [{ id: 'all', text: 'All', children: [{ id: 'item1', text: 'item1' }, { id: 'item2', text: 'item2' }] }]; $('.js-example-data-array').select2({data:data}); $('.js-example-data-array').select2('val',['item1']);
HTML:
<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