Cannot set select2 values

Viewed 1062

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
3 Answers

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();

First of all you need to return the selected values to the blade file from the controller.

Let the selected values be in $selected. Return it as

return view('posts', compact('selected'));

Then in your blade file you have to add the following script

 $(document).ready(function() {
      var selected = <?php echo json_encode($selected) ?>;
      $('#cat_select').select2();
      $('#cat_select').val(selected);
      $('#cat_select').trigger('change');
    });

This solution has been working for me and I have used it wherever I require select2 selected values.

Use this

$("#cat_select").select2('open');
var e = jQuery.Event("keyup");
e.which = 13;e.keyCode = 13;
$(".select2-search__field").val(data.title);
$(".select2-search__field").trigger(e);
$("#cat_select").select2('close');
Related