Reputation: 563
I use select2
As a result, I have a list on the backend
[
[12, "red fast car1"],
[45, "red big car2"],
[56, "red small table1"],
[34, "red fast car3"],
[77, "red big table"]
]
on request 'red car' need to get a list:
what match use for this?
My fiddle
Upvotes: 2
Views: 2443
Reputation: 11
@AlexandreS: You're a life saver mate! Your code written in coffeescript worked like a charm. For those looking for a vanilla JS, here's a code interpreted from @AlexandreS coffeescript code:
(function() {
$(function() {
var matcher;
return matcher = function(params, data) {
var terms, text;
if (params.term == null) {
return data;
}
terms = params.term.toUpperCase().split(' ');
text = data.text.toUpperCase();
if (terms.every(function(term) {
if (text.indexOf(term) > -1) {
return true;
}
})) {
return data;
} else {
return null;
}
};
});
$('.selectpicker').select2({
matcher: matcher
});
}).call(this);
Upvotes: 0
Reputation: 705
I stumbled upon this topic, thanks for pointing out you can use a custom matcher in select2.
Nonetheless, the interface seems to have changed since you wrote the fiddle, so here is the adaptation I had to write in coffeescript (⚠️ I don't use optgroups):
$ ->
matcher = (params, data) ->
if !params.term?
return data
terms = params.term.toUpperCase().split(' ')
text = data.text.toUpperCase()
if terms.every((term) -> return true if text.indexOf(term) > -1)
return data
else
return null
$('.selectpicker').select2({matcher: matcher});
Upvotes: 2
Reputation: 35253
You can split the term
at every <space>
and return true only if every
individual word matches the text
and label
const terms = term.split(' ');
return terms.every(term => {
if (text.indexOf(term) > -1 ||
(label !== undefined &&
label.toUpperCase().indexOf(term) > -1)) {
return true;
}
})
Upvotes: 2