Select2,当没有选项匹配时,“other”应该出现 [英] Select2, when no option matches, "other" should appear

查看:286
本文介绍了Select2,当没有选项匹配时,“other”应该出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用select2下拉列表,如果没有选项与用户输入的输入相匹配,如何显示默认选项?

With select2 dropdown, how do I get a default option to appear if no options match the user's typed input?

$("something").select2({
  formatNoMatches: function(term) {
    //return a search choice
  }
});

我无法在select2文档或Stack中找到任何与所需功能相匹配的内容溢出。

I haven't been able to find anything that really matches this desired functionality within the select2 documentation or Stack Overflow.

编辑
我越来越接近这个

Edit I'm getting closer with this

$("something").select2({
  formatNoMatches: function(term) {
    return "<div class='select2-result-label'><span class='select2-match'></span>Other</div>"
  }
});

但是这很糟糕,而且也无法点击。

But this is pretty hacky off the bat, and also isn't clickable.

推荐答案

补充@ vararis的答案:

To complement on @vararis's answer:

Select2附加到< select> 元素不允许自定义 createSearchChoice 查询函数,因此我们需要手动添加一个选项元素(我将它添加为元素的最后一个选项,这样我们就可以轻松地 .pop 它超出结果集):

Select2 attached to a <select> element does not allow for custom createSearchChoice nor query functions, hence we will need to manually add an option element (I'll add it as the last option of the element so we can easily .pop it out of the results set):

<select>
  ...
  <option value="0">Other</option>
</select>

然后传递一个自定义匹配器功能,以便这个其他选项总是匹配的。

Then pass a custom matcher function so that this "Other" option is always matched.

注意: Select2 3.4+使用不同的默认匹配器比文档中当前显示的那个,这个新的默认匹配器调用 stripDiacritics 函数,以便例如, a 匹配á。因此,我将应用页面中包含的Select2版本附带的默认匹配器,以将其默认匹配算法应用于任何不是其他选项的选项:

NOTE: Select2 3.4+ uses a different default matcher than the one currently shown in the documentation, this new one has a call to the stripDiacritics function so that a matches á for instance. Therefore I'll apply the default matcher that comes with the Select2 version included in the page to apply its default matching algorithm to any option that's not the "Other" option:

matcher: function(term, text) {
  return text==='Other' || $.fn.select2.defaults.matcher.apply(this, arguments);
},

最后,我们需要从结果集中删除其他选项当除了其他结果之外还有任何结果(最初总是在结果集中):

Finally, we need to remove the "Other" option from the results set when there's any result besides the "Other" result (which is initially always in the results set):

sortResults: function(results) {
  if (results.length > 1) results.pop();
  return results;
}

这篇关于Select2,当没有选项匹配时,“other”应该出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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