使用Select2的createSearchChoice函数 [英] Using Select2's createSearchChoice function

查看:223
本文介绍了使用Select2的createSearchChoice函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用createSearchChoice函数在默认列表不足时允许用户输入自己的选择.当我尝试在<select>元素上使用此功能时,出现以下错误:

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:

Error: Error: Option 'createSearchChoice' is not allowed for Select2 when attached to a <select> element.

我尝试改用<input type='hidden'>元素,但现在出现以下错误:

I tried using an <input type='hidden'> element instead, but now get the following error:

Error: uncaught exception: query function not defined for Select2 'MyInputName'

我宁愿使用select元素来与现有代码保持一致(需要选择多个选项的能力),但是除了从先前的列表中进行选择之外,用户还需要具有输入自己的选项的能力.

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.

推荐答案

哦,天哪,我该如何取消这一赏金.我惊慌失措,由于惊慌失措,我能够回答我们俩都在寻找的东西:

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:

您不能在select上使用createSearchChoice.因此,您必须使用input代替.

You can't use createSearchChoice on a select. So you have to use an input instead.

<input type="hidden" id="category">

解决方法是使用query参数:

$("#category").select2({query:function(query){
  var data = {results: []};
  data.results.push({text: query.term});
  query.callback(data);
}});

这是将当前术语添加到选项中(如果不存在的话).您可以像这样填充results对象:

What this does is add the current term to the options if it's not there. You can populate the results object like so:

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.

这篇关于使用Select2的createSearchChoice函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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