Mahdi Mahdi - 1 month ago 8
Javascript Question

Select2 val does not work for integer value

See in the Fiddle

I' m using JQuery select2 like the following

HTML

<select style="width:150px" id="lang" multiple >
<option value="1">1</option>
<option value="2">2</option>
<option value="11">3</option>
</select>


Javascript

$(document).ready(function() {
$('#lang').select2({
placeholder: 'please type'}
);
});


my problem is: I want to select an item programmatically

I use following code:

$("#lang").select2('val','11');


but the above code select the first item not the last one.

Answer

I believe...

$(element).select2();

...initializes Select2, rather than making a selection.

What you're probably looking for is something like this:

$("#lang").val("11").trigger("change");

If you want to select multiple values, you can use a string array, like so:

//Select 11, 12, 13
$("#lang").val(["11", "12", "13"]).trigger("change");

For more information, check out the Select2 Examples documentation.