After a lot of work on this issue ... I think I have a solution to this problem.
I noticed that Select2 seems to create its own structure inside the DOM - regardless of the choice you interact with. βIt is also completely independent of the choices you might have made elsewhere in the DOM.β
So ... After some messing around - I came up with the following code:
First: Create a global binding to all selections in the DOM. This is only for setting a temporary link to "what the current user is working with" - creating a global variable that can be used later.
$('select').select2().on('select2:open', function() { // set a global reference for the current selected Select console.log('found this ---> '+$(this).attr('id')); if (typeof tempSelectedObj === 'undefined') { tempSelectedObj = null; } tempSelectedObj = this; });
Second: Create a "keyup" event for the document that appears in Select2 time INPUT and select2-search__field. This will capture all key events for Select2 INPUT. But in this case, I added keyCode === 13 (return character) to start the magic.
$(document).on('keyup','input.select2-search__field',function (e) { // capture the return event if (e.keyCode === 13) { var newValue = $(this).val(); console.log('processing this: '+newValue); // create new option element var newOpt = $('<option>') .val(newValue) .text(newValue); // append to the current Select $(tempSelectedObj) .append(newOpt); // apply the change and set it $(tempSelectedObj) .val(newValue) .select2('close'); } })
When a return character is found, the following occurs.
- capture current value
- create a new DOM Option element (jQuery)
- set the value and text of the new Option element
- add new Option element to tempSelectedObj (jQuery) variable
- call Select2 to close
- set the value of Select2 to the new value added
- triggers a final change to Select2 to display a new option
- DONE!
Obviously, this example requires two sections of code, but I think this is a pretty attractive approach to a problem that many people seem to struggle with. And this is common enough that it could be easily adapted for other purposes.
Hope this helps! I struggled with this for a while.
Here is a working example:
https://jsfiddle.net/h690bkmg/1/
source share