jQuery 使用 Select2 的 createSearchChoice 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11674647/
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
Using Select2's createSearchChoice function
提问by jrrdnx
I'm trying to use the createSearchChoice function to allow users to enter their own choice when the default list won't suffice. When I try to use this function on a <select>
element, I get the following error:
我正在尝试使用 createSearchChoice 函数来允许用户在默认列表不够用时输入他们自己的选择。当我尝试在<select>
元素上使用此函数时,出现以下错误:
Error: Error: Option 'createSearchChoice' is not allowed for Select2 when attached to a <select> element.
Error: Error: Option 'createSearchChoice' is not allowed for Select2 when attached to a <select> element.
I tried using an <input type='hidden'>
element instead, but now get the following error:
我尝试改用一个<input type='hidden'>
元素,但现在出现以下错误:
Error: uncaught exception: query function not defined for Select2 'MyInputName'
Error: uncaught exception: query function not defined for Select2 'MyInputName'
I'd prefer to use the select element to stay in line with existing code (need the ability to select multiple options), but just need the ability for users to input their own option in addition to selecting from a prior list.
我更喜欢使用 select 元素来与现有代码保持一致(需要能够选择多个选项),但除了从先前的列表中进行选择之外,只需要用户能够输入自己的选项。
回答by Jürgen Paul
Oh God, How do I cancel this bounty. I panicked and due to panicking I was able to answer what we were both looking for:
天啊,我该如何取消这个赏金。我惊慌失措,由于惊慌失措,我能够回答我们都在寻找的问题:
You can't use createSearchChoice
on a select
. So you have to use an input
instead.
您不能createSearchChoice
在select
. 所以你必须使用 aninput
代替。
<input type="hidden" id="category">
The fix is to use the query
parameter:
解决方法是使用query
参数:
$("#category").select2({query:function(query){
var data = {results: []};
data.results.push({text: query.term});
query.callback(data);
}});
What this does is add the current term to the options if it's not there. You can populate the results
object like so:
这样做是将当前术语添加到选项中(如果它不存在)。您可以results
像这样填充对象:
var data = {results: [{text:'math'},{text:'science'}]};
This solved my problem so I hope it solved yours. I think we should read more on the documentation.
这解决了我的问题,所以我希望它解决了你的问题。我认为我们应该阅读更多关于文档的内容。
回答by Jeff Dickey
I had this problem and it was due to calling select2 on the same field twice
我遇到了这个问题,这是由于在同一个字段上调用 select2 两次