Search code examples
javascriptjqueryjquery-select2

Cannot set select2 values


I'm using Select2 v4 and I have the object initialized:

posts.blade.php

<select class="form-control" name="categories[]" multiple="multiple" id="cat_select">
  @foreach ($categories as $c)
   <option value="{{$c->id}}">{{$c->title}}</option>
  @endforeach
</select>

I already have it initiliased with default values that can be selected manually by the user. I have an ajax function that returns categories already initialised in the select. I want the returned data to be set in the select but it's not working. So for example the select already have option "sports", and from the ajax it returns "sports". I want "sports" to be selected.

javascript

let select_cat = $("select#cat_select").select2();

What I have tried

$("#cat_select").val([data.title]).trigger("change"); //which doesn't work for some reason

Solution

  • This was my solution. I had to destroy the select2, then added the values (array) to the select, and re-initialised it.

      data.categories.map(function(el){
        my_categories.push(el.id);
       });
      $("#cat_select").select2('destroy');
      $("#cat_select").val(my_categories);
      $("#cat_select").select2();