Programmatically select tags (custom ones)

Hi,

I can’t find how to select tags with select2.

I have a list of tags ids in the following format : tag1, customtag1, tag2

select2 is initialized on a select with static options.

<select id="myselect2" multiple>
  <option value="tag1">Tag1</option>
  <option value="tag2">Tag2</option>
</select>

If I try to use jQuery('#myselect2').val() with ["tag1", "customtag"] as parameter, only “tag1” will be selected (since “customtag” isn’t a static option in the select, it should be then considered as a new tag).

Minimal jsfiddle : http://jsfiddle.net/ThibautSF/m61o43q0/22/

Found a hack by simulating a user input : http://jsfiddle.net/ThibautSF/m61o43q0/25/

$("#myselect2").parent().find('.select2-search__field') //get user text input
    .val('tag1,customTag,') //apply list of tags (separated by tokenSeparators (should also end with one))
    .trigger('keyup'); //trigger event to simulate user input

Is there any better (and less dirty) way ? :smiley: