Reputation: 7465
I'm trying to use a custom matcher with the select2 library. Specifically, I want to return other
as the not-found option, as well as only match from the beginning of a string. I found the following to SO questions which answer each of these parts separately:
Select2, when no option matches, "other" should appear
and
jquery select2 plugin how to get only the result 'myString%'
However, when I combine the two techniques, it is no longer matching properly. My solution looks like:
$("#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 proper way to make this matcher function?
Upvotes: 5
Views: 19528
Reputation: 7465
I accomplished this using regular expressions and by splitting the conditional ||
into two steps. Final code was:
$("#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;
},
});
Upvotes: 6