如何使用Select2从原始选择中过滤掉选项标签?

问题描述 投票:3回答:4

看起来像一个非常简单的想法,但我无法弄清楚如何从select2下拉列表中过滤出原始选择的选项标签。

基本上,这个:

<select id="select">
    <option class="car">Car 1</option>
    <option class="plane">Plane 1</option>
</select>

$("#select").select2();

...应该只使用类car的选项标签创建一个假选择。

javascript jquery jquery-select2
4个回答
2
投票

看来OP在https://github.com/select2/select2/issues/1048找到了答案。

答案是提供matcher功能。

$("#select").select2({
    matcher: function(term, text, option) {
        return option.hasClass('car');
    }
});

jsfiddle


1
投票

您应该使用该选项的“禁用”属性。如果要将其过滤掉,请将其设置为“已禁用”。这在select2中将其灰显。或者,您可以使用CSS类隐藏它而不是灰色。


1
投票

只是为了使这个问题保持最新..使用提供matcher功能的建议答案已经过时。从Select2 4.0.0开始,你需要use a wrappermatcher

function matchStart (term, text) {
  if (text.toUpperCase().indexOf(term.toUpperCase()) == 0) {
    return true;
  }

  return false;
}

$.fn.select2.amd.require(['select2/compat/matcher'], function (oldMatcher) {
  $(".js-example-matcher-start").select2({
    matcher: oldMatcher(matchStart)
  })
});

对我而言,这不起作用。我不知道为什么。但我找到了解决方法。显然,使用Select2,您还可以为.select2()方法为select中的每个option或元素提供格式函数。例如,当您想要使用图标或类似的东西添加每个元素时。事实证明,如果在format函数中返回null,则该元素不会显示在下拉列表中,如下所示:

function formatState(state) {
            if (!state.id) { return state.text; }
            if (state.disabled) { return null; }
            var $state = $('<span>'.concat(state.text).concat("</span>"));
            return $state;
        }

$('#myDropdown').select2({
      templateResult: formatState
});

这对我很有用。也许它可以帮助你们当前的实现。


0
投票

我一直在努力解决问题,并发布了自己类似的question。上面提供的匹配器解决方案的问题是匹配器用于匹配搜索,而只是打开下拉列表将简单地匹配所有列表,因此显示不太令人满意的所有内容。

在最初的bug solution之后,我终于使用'破坏'select2并在过滤选择后重建它。以下是使用此方法的问题的解决方案,

//assuming you are usign jquery...
//keep a non-filtered copy of the original select
var $clonedSelect = $('select#select').clone();
$.fn.filterSelect2 = function(class=''){
  if( $(this).is('select') ){
    $(this).select2('destroy');
    $(this).empty();
    $(this).append( $('option.'+class, $clonedSelect).clone() );
    $(this).select2();
  }
  return $(this);
}
$('select#select').filterSelect2('car'); //will create a select2 with only the car class options.

我没有对此进行过测试,但我在最近的一个项目中使用了类似的逻辑来处理更复杂的情况,并发现它工作得非常好。

© www.soinside.com 2019 - 2024. All rights reserved.