Select2事件用于创建新标签 [英] Select2 Event for creating a new tag

查看:316
本文介绍了Select2事件用于创建新标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为标签选择器使用jQuery Select2 (v4)插件。

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

我想监听在select元素中创建新标记并激活ajax请求以存储新标记。我发现有 createTag 事件,但每次在select2元素中输入一个字母时,这似乎都会触发。如我的小提琴所示: http://jsfiddle.net/3qkgagwk/1/

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.

推荐答案

我遗憾地找不到任何原生方法。但是如果你对简单的变通方法感兴趣,也许这会让你更接近:

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



(小更新:请参阅 @Alex 以下评论)

只有使用鼠标添加标签时,上述操作才有效。对于通过点击 space 逗号添加的标签,请使用更改事件。

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

然后你可以用过滤选项 data-select2-tag =true属性(新添加的标签):

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

这篇关于Select2事件用于创建新标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆