Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting a value in select2 having optGroup

Tags:

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?

like image 435
stack_alok Avatar asked May 04 '15 16:05

stack_alok


People also ask

How do I assign a value to select2?

$("#programid"). select2({ placeholder: "Select a Program", allowClear: true, minimumInputLength: 3, ajax: { url: "ajax.

How do I add options in Select 2?

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 enable search in select2?

var data = []; // Programatically-generated options array with > 5 options var placeholder = "select"; $(". mySelect"). select2({ data: data, placeholder: placeholder, allowClear: false, minimumResultsForSearch: 5});


2 Answers

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"); 
like image 137
Lelio Faieta Avatar answered Oct 23 '22 16:10

Lelio Faieta


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> 
like image 25
datchung Avatar answered Oct 23 '22 16:10

datchung