Sayantan Das Sayantan Das - 7 days ago 6
Javascript Question

Select2 multiple select default selections not working

This is my html code

<select name="age_group[]" class="form-control age_group" multiple="multiple">
@foreach($age_groups as $group)
<option value="{{ $group->id }}">{{ $group->age_group_name }}</option>
@endforeach
</select>


And this is the JS

var selected = [1, 2, 3];
// initialize select2 for age group
$(".age_group").select2();
$(".age_group").select2('val', selected);


What I want to do is set default values as selected as suggested by this post. But in my code above I am only getting the first element of the array as selected.

Can anyone tell me what's wrong with my code?

Jsfiddle demo

Answer

Try like this it will work:

$(".age_group").val(selectedvalue).trigger("change");

sample fiddle : http://jsfiddle.net/fyhsz9ra/891/

Comments