1

I am using the select2 JQuery plugin. The first option in the dropdown is labeled "All Organizations". When users search for an option, I don't want to include that first "All Organizations" option in the search results.

Is there an easy way of doing this?

It seems that the strategy would be to use a custom matcher and return null if I see that option. However, then I would need to code up the rest of the matcher, which would basically do the same thing as the default behavior. Can I somehow call the original matcher from within my custom matcher?

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

function custMatcher(params, data) {
    if (params.term === "All Organizations") {
        return null;
    }

    // else do regular searching
    // would like to call the original matcher here.
 }

jsfiddle

pushkin
  • 9,575
  • 15
  • 51
  • 95

1 Answers1

6

Here we go ;)

var defaultMatcher = $.fn.select2.defaults.defaults.matcher;
function customMatcher(params, data) {
  if (params.term && data.id == "ALL") 
   return null;
  return defaultMatcher(params, data);
}
$("#s").select2({
 matcher: customMatcher,
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>

<select id="s">
<option value="ALL">All Organizations</option>
<option value="1">Org 1</option>
</select>
bigless
  • 2,849
  • 19
  • 31
  • Thanks! I guess I was really hoping that someone would say "actually you don't need a customer matcher, just turn on this flag when you're setting it up." – pushkin Oct 05 '17 at 18:24
  • I think that best solution is [using placeholder](https://stackoverflow.com/questions/21413241/how-to-use-placeholder-as-default-value-in-select2-framework), but you asked for default matcher – bigless Oct 05 '17 at 18:47
  • Yeah, I saw that, but I don't think I want a placeholder. I want it to be an option, just not one that's searchable. – pushkin Oct 05 '17 at 18:52
  • Ok. I got it ;) – bigless Oct 05 '17 at 19:18