Martijn de Milliano Martijn de Milliano - 1 year ago 83
Javascript Question

How to trigger tag creation in select2 single select (e.g. when adjacent button is pressed)?

I am using select2 4.0.3. I have a select2 box to enter email addresses, and I would like to make sure that all email addresses are included in

, also the one that the user was still typing in the search field.

Form element

The form field is referenced by
. When I press the Send button, in the event handler
just gives me the first two addresses
, but not the third address (

This is how I initialize the select2 element:

tags: true,
tokenSeparators: [',', ' '],
selectOnBlur: true

has no effect, and I cannot find anything else that works on select2 v4. I tried firing several events at various elements, none of it worked.

I expect that when I press the Send button, that I can make some call to the select2 box to trigger creating a tag for the contents of whatever is then in the search field
, and that subsequently
returns an array with all three addresses.

Update: I created a jsFiddle for you to play with. Enter input like this:

View of jsFiddle before pressing Send button

and then press the Send button, you will see:

View of jsFiddle after pressing Send

is missing from the output.

Note that in my real application I have disabled the dropdown because I just want the tagging behaviour.

Answer Source

You need to add selectOnClose and set it to true so that it creates the tag for you when you close / click off of the search input.

  selectOnClose: true

See the official documentation here:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download