I have a use case where I allow people to type values into the text box of the select2 plugin that do not appear in the select list.
In one case I am providing validation and do not submit unless the user has a valid item selected but until they do I do not want to clear their values. The select box might contain 1.00, 1.50, 1.75, NA, ABS and the user has just typed 1.80. This is an invalid value but I don't want to lose their changes, I will flag that box as invalid and allow them to fix their changes. I do not want to add 1.80 to the select box as it is an invalid value, but I don't want to clear it either.
How is it possible to achieve this?
To set selected value of jQuery Select2 with JavaScript, we call val and then trigger . Then we set its value with val to the option with value 0. Finally, we call trigger with 'change' to update the drop down to show the value we set.
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).
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.
InitSelection. This decorator provides backwards compatibility for the initSelection callback in version 3.5. In the past, Select2 required an option called initSelection that was defined whenever a custom data source was being used, allowing for the initial selection for the component to be determined.
If you're validating in JS, Select2 has an example for dynamic loading/generating data which overrides query() to just repeats the user's input.
See: http://ivaynberg.github.io/select2/ 'Loading Data'
I solved a similar problem (server-side) with JQuery UI 'autocomplete'. Here, I took the approach of returning objects wrapping both a label with possible explanatory message, a text value without decoration, and a combined ID value & status flag. I overrode select
to store the Text & ID to hidden fields.
In my case, I was distinguishing between existing Customers to reference, or creating a new Customer with the entered name. I was able to list options of matching existing customers or creating "ABC New Customer", quite nicely:
User enters: "Alphabet Soup" and sees a choice of:
A similar technique might be applicable to you. Hope this helps.
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