select2 search - match only words that start with search term

Mindaugas Li picture Mindaugas Li · Jul 22, 2015 · Viewed 21.8k times · Source

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.

Answer

Arturo Montoya picture Arturo Montoya · Jun 29, 2016

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