16

I migrated from chosen to select2 plugin because it works better for me, but its documentation is very poor when compared to chosen. Could anyone tell me what option(s) should be used to make select2 search function to filter words that just begin with search term (and don't contain it in the middle).

Let's say select2 field has those options: banana, apple, pineapple.

When user enters "app" (or apple), only apple should be returned (because it's the only word that starts with apple). Now, it returns both apple and pineapple.

After lots of search I figured out that some custom matcher needs to be used, but that's all so far.

4

2 回答 2

30

选择2 4.0.0

function matchStart(params, data) {
    params.term = params.term || '';
    if (data.text.toUpperCase().indexOf(params.term.toUpperCase()) == 0) {
        return data;
    }
    return false;
}

$("select").select2({
    matcher: function(params, data) {
        return matchStart(params, data);
    },
});

于 2016-06-29T01:40:18.370 回答
21

Select2在文档中提供了一个示例,说明如何使用自定义matcher函数将搜索词与搜索结果进行匹配。给出的示例就是这个确切的用例。

function matchStart (term, text) {
  if (text.toUpperCase().indexOf(term.toUpperCase()) == 0) {
    return true;
  }
 
  return false;
}
 
$.fn.select2.amd.require(['select2/compat/matcher'], function (oldMatcher) {
  $("select").select2({
    matcher: oldMatcher(matchStart)
  })
});
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.css" rel="stylesheet"/>

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.full.js"></script>

<select style="width: 200px">
  <option value="AL">Alabama</option>
  <option value="AK">Alaska</option>
  <option value="AZ">Arizona</option>
</select>

于 2015-07-22T23:28:43.893 回答