Is it possible to search on a combination of the text and another attribute in select2? For example, can the user search on both the value of "data-test" and text below:
<option value="185" data-test="5">Test</option>
<option value="186" data-test="6">Test 2</option>
<option value="187" data-test="7">Test 3</option>
Such that searching for "Test 2" and "6" show the same single option?
This is on a list bound at the page load, so it can't be filtered elsewhere.
Thanks -
It's simple enough once found -
Create a custom matching function, similar to "matcher" in select2.js:
function customMatcher(params, data) {
// Always return the object if there is nothing to compare
if ($.trim(params.term) === '') {
return data;
}
... OTHER MATCHING CODE
// Check if the text contains the term
if (original.indexOf(term) > -1) {
return data;
}
// Check if the data occurs
if ($(data.element).data('test').toString().indexOf(params.term) > -1) {
return data;
}
// If it doesn't contain the term, don't return anything
return null;
}
I added the "data('test')" to the function above and updated the initialization to:
$("#ddl").select2({
matcher: customMatcher
});
Works great.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With