Select2 Custom Matcher

I am trying to use special matches with select2 library. In particular, I want to return otheras not found option, and also only coincidence with the beginning of the line. I found the following SO questions that answer each of these parts separately:

Select2, when there is no option, "other" should appear

and

jquery select2 plugin how to get only result 'myString%'

However, when I combine the two methods, it no longer fits correctly. My solution looks like this:

$("#myForm").select2({
    minimumInputLength: 2,
    width: width,
    matcher: function(term, text) {
        // THIS IS WHERE I COMBINE THE METHODS
        return text === 'Other' || text.toUpperCase().indexOf(term.toUpperCase())==0;
    },
    sortResults: function(results) {
        if (results.length > 1) results.pop();
            return results;
    }
});

What am I doing wrong, and what is the correct way to make this contemplative function?

+4
source share
1 answer

, , || . :

$("#myForm").select2({
    minimumInputLength: 2,
    width: width,
    matcher: function(term, text) {
        var terms = term.split(" ");
        for (var i=0; i < terms.length; i++){
            var tester = new RegExp("\\b" + terms[i], 'i');
            if (tester.test(text) == false){
                return (text === 'Other')
            }
        }
        return true;
    },
    sortResults: function(results) {
        if (results.length > 1) {
            results.pop();
        }
        return results;
    },
});
+3

Source: https://habr.com/ru/post/1548154/


All Articles