javascript Select2 下拉菜单允许用户输入新值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25616520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 04:44:43  来源:igfitidea点击:

Select2 dropdown allow new values by user when user types

javascriptjqueryjquery-select2

提问by Alireza Fattahi

The select2 component can be configured to accept new values, as ask in Select2 dropdown but allow new values by user?

select2 组件可以配置为接受新值,如Select2 下拉列表中所问但允许用户使用新值?

And you can see it at: http://jsfiddle.net/pHSdP/646/the code is as below:

你可以在:http: //jsfiddle.net/pHSdP/646/看到它,代码如下:

$("#tags").select2({
    createSearchChoice: function (term, data) {
        if ($(data).filter(function () {
            return this.text.localeCompare(term) === 0;
        }).length === 0) {
            return {
                id: term,
                text: term
            };
        }
    },
    multiple: false,
    data: [{
        id: 0,
        text: 'story'
    }, {
        id: 1,
        text: 'bug'
    }, {
        id: 2,
        text: 'task'
    }]
});

The problem is that the new value is only added to the list if you enter new value and press enter, or press tab.

问题是只有在输入新值并按 Enter 或按 Tab 时,新值才会添加到列表中。

Is it possible to set the select2 component to accept this new value when use types and leave the select2. (Just as normal html input tag which keeps the value which you are typing when you leave it by clicking some where on the screen)

是否可以将 select2 组件设置为在使用类型时接受此新值并保留 select2。(就像普通的 html 输入标签一样,当你点击屏幕上的某个位置时,它会保留你正在输入的值)

I found that the select2 has select2-blurevent but I don't find a way to get this new value and add it to list?!

我发现 select2 有select2-blur事件,但我没有找到获取这个新值并将其添加到列表的方法?!

回答by Jason

Adding attribute selectOnBlur: true,seems to work for me.

添加属性selectOnBlur: true,似乎对我有用。

Edit: glad it worked for you as well!

编辑:很高兴它也对你有用!

回答by Char

I am using Select2 4.0.3 and had to add two options:

我正在使用 Select2 4.0.3 并且必须添加两个选项:

tags: true,
selectOnBlur: true,

This worked for me

这对我有用

回答by Sergii Shcherbak

And to be able to submit multiple new choices together with the existing ones:

并且能够与现有选项一起提交多个新选项:

select2({tags: true, selectOnBlur: true, multiple: true})