Search code examples
jqueryjquery-select2jquery-select2-4

Select2 4.0.1: How to return only first character matched results?


I am using Select2 Version 4.0.1, while searching any name, I would like to show only those records which is matched by first character. eg: I start from "c" then show only those names which start from "c". See attachment.

I tried different methods was available on stackoverflow, but no luck. eg: tried this one also, but got this error "select2 text.toUpperCase is not a function"

$("select").select2({
    matcher: function(term, text) {
      return text.toUpperCase().indexOf(term.toUpperCase())==0;
    }
});

enter image description here


Solution

  • Do you use the full version of select2 ? if yes, try this exemple

    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)
      })
    });