Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select2 Event for creating a new tag

I'm using the jQuery Select2 (v4) plugin for a tag selector.

I want to listen for when a new tag is created in the select element and fire an ajax request to store the new tag. I discovered there is the createTag event but this seems to fire every time a letter is entered into the select2 element. As shown in my fiddle: http://jsfiddle.net/3qkgagwk/1/

Is there a similar event that only fires when the new tag has finished being entered? I.e. it's enclosed by a grey box enclosing it.

like image 428
harryg Avatar asked Feb 22 '15 10:02

harryg


People also ask

What triggers an event Choose 2?

Select2 will trigger a few different events when different actions are taken using the component, allowing you to add custom hooks and perform actions. You may also manually trigger these events on a Select2 control using . trigger .

What is Select2 tag?

Select2 gives you a customizable select box with support for searching, tagging, remote data sets, infinite scrolling, and many other highly used options.

How do you add new option if not exist in the list using Select2?

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).


3 Answers

I can't find any native method unfortunately. But if you're interested in simple "workarounds", maybe this get you closer:

$('.select2').select2({     tags: true,     tokenSeparators: [",", " "],     createTag: function (tag) {         return {             id: tag.term,             text: tag.term,             // add indicator:             isNew : true         };     } }).on("select2:select", function(e) {     if(e.params.data.isNew){         // append the new option element prenamently:         $(this).find('[value="'+e.params.data.id+'"]').replaceWith('<option selected value="'+e.params.data.id+'">'+e.params.data.text+'</option>');         // store the new tag:         $.ajax({             // ...          });     } }); 

DEMO


[EDIT]
(Small update: see @Alex comment below)

The above will work only if the tag is added with mouse. For tags added by hitting space or comma, use change event.

Then you can filter option with data-select2-tag="true" attribute (new added tag):

$('.select2').select2({     tags: true,     tokenSeparators: [",", " "] }).on("change", function(e) {     var isNew = $(this).find('[data-select2-tag="true"]');     if(isNew.length && $.inArray(isNew.val(), $(this).val()) !== -1){         isNew.replaceWith('<option selected value="'+isNew.val()+'">'+isNew.val()+'</option>');         $.ajax({             // ... store tag ...         });     } }); 

DEMO 2

like image 88
Artur Filipiak Avatar answered Oct 03 '22 13:10

Artur Filipiak


The only event listener that worked for me when creating a new tag was:

.on("select2:close", function() {  (my code) }) 

This was triggered for new tags and selecting from the list. change, select2:select, select2:selecting and any others did not work.

like image 29
Pseudo-Hippy Avatar answered Oct 03 '22 12:10

Pseudo-Hippy


One more simple check will be this based on the difference in the args of the event .....

While I was dealing with this situation, I had seen this difference; that when the new element is created the event args data does not have an element object but it exists when selecting an already available option...

.on('select2:selecting', function (e) {
   if (typeof e.params.args.data.element == 'undefined') {  
      // do a further check if the item created id is not empty..
       if( e.params.args.data.id != "" ){
          // code to be executed after new tag creation
       }
   }
 })

See this picture for different condition's event log

like image 36
TheVigilant Avatar answered Oct 03 '22 12:10

TheVigilant