Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass array to val in Select2

I have a problem to set the selected Values of my "Select2". When I pass the id values separated by commas it works. But if the pass like array doesn't work.

this is my Select

<select class="form-control" id="myselect" multiple="multiple">
<option id="1">Value1</option>
<option id="2">Value2</option>
<option id="3">Value3</option>
<option id="4">Value4</option>
<option id="5">Value5</option>
</select>     

It works

$("#myselect").select2().select2('val', [1,2,3]);

but this dosn't work

var array_selection = [1,2,3];
$("#myselect").select2().select2('val', [array_selection]);
like image 657
Manuel Pena Avatar asked Mar 10 '26 03:03

Manuel Pena


1 Answers

You are putting your array_selection Array into another Array. Change

var array_selection = [1,2,3];
$("#myselect").select2().select2('val', [array_selection]);

to

var array_selection = [1,2,3];
$("#myselect").select2().select2('val', array_selection);
like image 56
StackSlave Avatar answered Mar 12 '26 16:03

StackSlave