Friday, October 21, 2016

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

Leave a Comment

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 .val(), also the one that the user was still typing in the search field.

Form element

The form field is referenced by $('.invite-emails-field'). When I press the Send button, in the event handler $('.invite-emails-field').val() just gives me the first two addresses test1@example.com and test2@example.com, but not the third address (test3@example.com).

This is how I initialize the select2 element:

$('.invite-emails-field').select2({   tags: true,   tokenSeparators: [',', ' '],   selectOnBlur: true }); 

The selectOnBlur 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 test3@example.com, and that subsequently .val() 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

where test3@example.com is missing from the output.

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

1 Answers

Answers 1

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.

$('select').select2({   selectOnClose: true }); 

See the official documentation here: https://select2.github.io/options.html#can-i-select-the-highlighted-result-when-the-dropdown-is-closed

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment