使用 Select2 的 createSearchChoice 函数
-
12-12-2019 - |
题
我试图使用 createSearchChoice 函数来允许用户在默认列表不够时输入自己的选择。当我尝试在 <select>
元素,我收到以下错误:
Error: Error: Option 'createSearchChoice' is not allowed for Select2 when attached to a <select> element.
我尝试使用 <input type='hidden'>
元素代替,但现在出现以下错误:
Error: uncaught exception: query function not defined for Select2 'MyInputName'
我更喜欢使用 select 元素来与现有代码保持一致(需要能够选择多个选项),但只需要用户除了从先前的列表中进行选择之外还能够输入自己的选项。
解决方案
天哪,我该如何取消这个赏金。我惊慌失措,由于惊慌,我能够回答我们都在寻找的问题:
你不能使用 createSearchChoice
在一个 select
. 。所以你必须使用 input
反而。
<input type="hidden" id="category">
修复方法是使用 query
范围:
$("#category").select2({query:function(query){
var data = {results: []};
data.results.push({text: query.term});
query.callback(data);
}});
其作用是将当前术语添加到选项中(如果不存在)。您可以填充 results
像这样的对象:
var data = {results: [{text:'math'},{text:'science'}]};
这解决了我的问题,所以我希望它能解决你的问题。我认为我们应该阅读更多关于 文档.
其他提示
我遇到了这个问题,这是由于在同一字段上调用 select2 两次
不隶属于 StackOverflow