使用select2显示与optgroup匹配的结果

时间:2014-02-24 16:02:44

标签: jquery-select2 optgroup

我正在使用select2和Bootstrap 3。 现在我想知道,如果搜索与optgroup名称匹配,是否可以显示所有optgroup项目,同时仍能搜索项目。如果可以,我该怎么办?

3 个答案:

答案 0 :(得分:21)

通过修改匹配器

实际上找到了解决方案
 $("#myselect").select2({
    matcher: function(term, text, opt){
         return text.toUpperCase().indexOf(term.toUpperCase())>=0 || opt.parent("optgroup").attr("label").toUpperCase().indexOf(term.toUpperCase())>=0
    }
});

在每个optgroup中设置label属性的前提下。

答案 1 :(得分:18)

以上答案似乎不适用于Select2 4.0,所以如果你正在寻找它,请查看:https://github.com/select2/select2/issues/3034

(使用如下函数:$("#example").select2({matcher: modelMatcher});

function modelMatcher (params, data) {
  data.parentText = data.parentText || "";

  // Always return the object if there is nothing to compare
  if ($.trim(params.term) === '') {
    return data;
  }

  // Do a recursive check for options with children
  if (data.children && data.children.length > 0) {
    // Clone the data object if there are children
    // This is required as we modify the object to remove any non-matches
    var match = $.extend(true, {}, data);

    // Check each child of the option
    for (var c = data.children.length - 1; c >= 0; c--) {
      var child = data.children[c];
      child.parentText += data.parentText + " " + data.text;

      var matches = modelMatcher(params, child);

      // If there wasn't a match, remove the object in the array
      if (matches == null) {
        match.children.splice(c, 1);
      }
    }

    // If any children matched, return the new object
    if (match.children.length > 0) {
      return match;
    }

    // If there were no matching children, check just the plain object
    return modelMatcher(params, match);
  }

  // If the typed-in term matches the text of this term, or the text from any
  // parent term, then it's a match.
  var original = (data.parentText + ' ' + data.text).toUpperCase();
  var term = params.term.toUpperCase();


  // Check if the text contains the term
  if (original.indexOf(term) > -1) {
    return data;
  }

  // If it doesn't contain the term, don't return anything
  return null;
}

答案 2 :(得分:0)

在没有父级optgroups的情况下,对人们进行了一些细微的更改建议代码,减少了重复性和应对措施:

$('select').select2({
    matcher: function(term, text, opt){
        var matcher = opt.parent('select').select2.defaults.matcher;                        
        return matcher(term, text) || (opt.parent('optgroup').length && matcher(term, opt.parent('optgroup').attr("label"))); 
    }
});