javascript 使用 Select2 从单个选择框中获取用户输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18916899/
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-27 13:40:43  来源:igfitidea点击:

Get user input from single select box using Select2

javascriptjqueryformsjquery-select2

提问by james

Issue

问题

I just started using Select2(http://ivaynberg.github.io/select2/) and I am trying to do a basic task.

我刚开始使用Select2( http://ivaynberg.github.io/select2/),我正在尝试做一个基本的任务。

I have a select box that has, for example, 3 items in it. I want to be able to have the user either select 1 of the 3 results or type in their own result and then eventually, on submit, it will submit whatever value is in the box.

我有一个选择框,例如,里面有 3 个项目。我希望能够让用户选择 3 个结果中的 1 个或输入他们自己的结果,然后最终在提交时,它将提交框中的任何值。

What I've Tried

我试过的

<input style="width: 200px;" type="hidden" id="foo" />

<script type="text/javascript">
$(document).ready(function () {
        $("#foo").select2({
            query: function (query) {
                var data = { results: [{ text: 'math' }, { text: 'science' }, { text: 'english' }] };
                data.results.push({ text: query.term });
                query.callback(data);
            }
        });
    });
</script>

The code above allows me to see the 3 results and type in a result myself. But I am unable to get the typed in result to "stick" when I click away, hit enter, or select the result I just typed in. Same goes for the select options, but I am most concerned with the user inputted text.

上面的代码允许我查看 3 个结果并自己输入结果。但是当我点击离开、回车或选择我刚刚输入的结果时,我无法让输入的结果“粘住”。选择选项也是如此,但我最关心的是用户输入的文本。

Here's what it looks like:

这是它的样子:

http://i.imgur.com/XPnPR8H.png

http://i.imgur.com/XPnPR8H.png

采纳答案by Daru

The parameter createSearchChoice allows you to do just what you want. Here is an example:

参数 createSearchChoice 允许您做您想做的事。下面是一个例子:

<script type="text/javascript">
    $("#foo").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'}]
    });
</script>

Taken from a closed issue at: https://github.com/ivaynberg/select2/issues/201

摘自已关闭的问题:https: //github.com/ivaynberg/select2/issues/201

Fiddle: http://jsfiddle.net/pHSdP/2/

小提琴:http: //jsfiddle.net/pHSdP/2/

Also, make sure you add a name to the input, otherwise you won't see the value at server side

另外,请确保在输入中添加名称,否则您将看不到服务器端的值

<input style="width: 200px;" type="hidden" id="foo" name="foo" />

回答by Duc Hong

Just a quick note for anyone else who's having a different data input. In case the console says " this.text is undefined ", make sure you check your text tag, like this:

对于有不同数据输入的其他人来说,这只是一个简短的说明。如果控制台显示“ this.text 未定义”,请确保检查您的文本标签,如下所示:

<script type="text/javascript">
    // Data input taken from "label", not "text" like usual
    var lstData = [{id: 0, 'label': 'story'},{id: 1, 'label': 'bug'},{id: 2, 'label': 'task'}];
    $("#foo").select2({
        createSearchChoice:function(term, data) {
            if ($(data).filter(function() {
                return this.label.localeCompare(term)===0; }).length===0) {
                    return {id:term, 'label':term};
                }
            },
        data: { results: lstData, text: 'label' }
    });
</script>

回答by Srihari

Library you are using is used to filter options in a select box. It doesn't take new input, as per their own documentation:

您正在使用的库用于过滤选择框中的选项。根据他们自己的文档,它不需要新的输入:

Select2 is a jQuery based replacement for select boxes.It supports searching, remote data sets, and infinite scrolling of results.

Select2 是一个基于 jQuery 的选择框替代品。它支持搜索、远程​​数据集和结果的无限滚动。

I would suggest you to use jQueryUI Autocompleteor TypeAhead

我建议你使用jQueryUI AutocompleteTypeAhead