1

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

Community
  • 1
  • 1
Sayantan Das
  • 1,619
  • 4
  • 24
  • 43

2 Answers2

2

Try like this it will work:

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

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

Santhucool
  • 1,656
  • 2
  • 36
  • 92
0

You need to specify the value you need to select.

$('select').select2().select2('val', $('.select2 option:eq(1)').val());

OR

Split the values before Passing to the Select2();
var values = //split the string ;
$(".age_group").select2('val',values);

Hope this Helps you.

Rohit shah
  • 833
  • 4
  • 15
  • I have not tried your first option as the other answer worked but your second option is same as i was doing . `values` in my case is already an array. – Sayantan Das Nov 29 '16 at 05:39