Sayantan Das Sayantan Das - 2 months ago 29
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>

And this is the JS

var selected = [1, 2, 3];
// initialize select2 for age group
$(".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


Try like this it will work:


sample fiddle :