Select2 Event for creating a new tag

匆匆过客 提交于 2019-11-30 11:32:20

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

Another workaround. Just insert it to the beginning:

           }).on('select2:selecting', function (evt) {

             var stringOriginal = (function (value) {
                // creation of new tag
                if (!_.isString(value)) {
                    return  value.html();
                }
                // picking existing
                return value;
            })(evt.params.args.data.text);
            ........

It relies on underscore.js for checking if it's string or not. You can replace _.isString method with whatever you like.

It uses the fact that when new term is created it's always an object.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!