Select2 Event for creating a new tag

harryg picture harryg · Feb 22, 2015 · Viewed 24.8k times · Source

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.

Answer

Artur Filipiak picture Artur Filipiak · Feb 22, 2015

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