How to initiate the creation of tags in select2 single select (for example, when pressing the adjacent button)?

I am using select2 4.0.3. I have a select2 field for entering email addresses, and I would like to make sure that all email addresses are included in .val() , as well as the one that the user is still typing in the search box.

Form element

The form field says $('.invite-emails-field') . When I click the send button, 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 }); 

selectOnBlur no effect, and I can not find anything that works on select2 v4. I tried to trigger several events on different elements, none of them worked.

I expect that when I click the "Send" button, I can call the select2 field to cause a tag to be created for the contents of what is in the test3@example.com search field and that subsequently .val() returns an array with all three addresses .

Update: I created jsFiddle for you. Enter the input as follows:

View jsFiddle before clicking submit button

and then click the "Submit" button, you will see:

View jsFiddle after clicking Submit

where test3@example.com missing from the output.

Please note that in my real application I turned off the dropdown menu because I just need to flag the behavior.

+7
javascript jquery select2
source share
1 answer

You need to add selectOnClose and set it to true so that it creates a tag for you when you close / turn off the input for searching.

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

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

+6
source share

All Articles