Why select2 not set all array elements?

Viewed 46

Here I have custom code where I test set array to select2 value. But when I set array items to select2, all items not have setted. How can be solved this problem?

$('#tags').select2({
  multiple:true,
  tags: true,
  placeholder: 'Select tag...'
});

var tags = ["design", "template"];

$('#setTags').click(
  function(e) {
    $('#tags').select2('val', tags);
  }
);
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.3.1.min.js
"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>

<select name="tags[]" id="tags" multiple="multiple">
  <option value="design">Design</option>
  <option value="portfolio">Portfolio</option>
  <option value="template">Template</option>
</select>

<button id="setTags">Set tags</button>

1 Answers

You need to replace $('#tags').select2('val', tags); to $('#tags').val(tags); then trigger change event like this.

$('#tags').select2({
  multiple:true,
  tags: true,
  placeholder: 'Select tag...'
});

var tags = ["design", "template"];

$('#setTags').click(
  function(e) {
    $('#tags').val(tags);
    $('#tags').trigger('change');
  }
);
#tags {
   width: 100%;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.3.1.min.js
"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>

<select name="tags[]" id="tags" multiple="multiple">
  <option value="design">Design</option>
  <option value="portfolio">Portfolio</option>
  <option value="template">Template</option>
</select>

<button id="setTags">Set tags</button>

Reference

Related