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.
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 [email protected]
and [email protected]
, but not the third address ([email protected]
).
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 [email protected]
, 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:
and then press the Send button, you will see:
where [email protected]
is missing from the output.
Note that in my real application I have disabled the dropdown because I just want the tagging behaviour.
HTML. Create a <select class="select2_el" > element to initialize select2 on page load and create <div id="elements" > container to store <select > element on button click using jQuery AJAX.
Select2 gives you a customizable select box with support for searching, tagging, remote data sets, infinite scrolling, and many other highly used options.
New options can be added to a Select2 control programmatically by creating a new Javascript Option object and appending it to the control: var data = { id: 1, text: 'Barn owl' }; var newOption = new Option(data. text, data.id, false, false); $('#mySelect2'). append(newOption).
By default, Select2 will attach the dropdown to the end of the body and will absolutely position it to appear above or below the selection container. Select2 will display the dropdown above the container if there is not enough space below the container, but there is enough space above it.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With