Programmatically select tags (custom ones)


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>

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 :

Found a hack by simulating a user input :

$("#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: