3

I want to write a custom select2 (versions 4.0) matcher such that dots and whitespaces are ignored when a search is performed.

Eg. If one of the option is Dr. R. N. Pandey, I should be able to find Dr. R. N. Pandey just by typing rnp in the search box.

abhishek77in
  • 1,848
  • 21
  • 41

2 Answers2

1

Please try this:

HTML:

<select class='select2'>
    <option>Select</option>
    <optgroup label="Vegetables">
        <option>A. Celery</option>
        <option>Green R.P Pepper</option>
        <option>Kale</option>
    </optgroup>
    <optgroup label="Fruits">
        <option>Apple</option>
        <option>Orange</option>
        <option>Banana</option>
    </optgroup>
    <optgroup label="Nuts" disabled>
        <option>Almond</option>
        <option>Walnut</option>
        <option>Pine</option>
    </optgroup>
</select>

JS:

(function() {
    function matcher(term, text) {

        term = term.toUpperCase();
        text = text.toUpperCase().replace(/\./g, '').replace(/\s+/g, '');

        if (text.indexOf(term) > -1 ) {
            return true;
        }

        return false;
    }

    $(".select2").select2({
        matcher: matcher
    });
})();

Please have a look from the demo(<4.0):

https://jsfiddle.net/xfw4tmbx/22/

select 2 version 4.0

https://jsfiddle.net/11a998kw/1/

sharif2008
  • 2,716
  • 3
  • 20
  • 34
1

Inspired by answer already provided:

  function ignoreDotAndWhitespace(params, data) {
    params.term = params.term || '';

    term = params.term.toUpperCase();
    text = data.text.toUpperCase().replace(/\./g, '').replace(/\s+/g, '');

    if (text.indexOf(term) > -1 ) {
      return data;
    }
    return false;
  }

  $('.select2').select2({
    matcher: function(params, data) {
      return ignoreDotAndWhitespace(params, data);
    }
  });
abhishek77in
  • 1,848
  • 21
  • 41