'Filter by id as well as text in Select2
var data = [{ id: 11-07, text: 'enhancement' }, { id: 11-04, text: 'bug' },
{ id: 11-08, text: 'duplicate' }, { id: 11-09, text: 'invalid' },
{ id: 11-10, text: 'wontfix' }];
$(".js-example-data-array").select2({
data: data
})
<select class="js-example-data-array"></select>
I want to filter the select2 with both id as well as text. By default , it filters by text. How can I filter by id as well?
Solution 1:[1]
You must use "matcher".
$(".js-example-data-array").select2({
data: data,
matcher: function(term, text, option) {
return text.toUpperCase().indexOf(term.toUpperCase())>=0 || option.val().toUpperCase().indexOf(term.toUpperCase())>=0;
}
})
It will return result filtered by text or id.
Solution 2:[2]
Use a a custom matcher. Add a property "matcher" with an custom function so you can match it your self. For explanation check the examples page. To match against the id you need to use a 'complex matcher'. More info about that can be found here.
Solution 3:[3]
For the current 4th version the function for the matcher
must be written differently. This code is based on an example from the documentation:
$(document).ready(function() {
var data = [{ id: '11-07', text: 'enhancement' }, { id: '11-04', text: 'bug' },
{ id: '11-08', text: 'duplicate' }, { id: '11-09', text: 'invalid' },
{ id: '11-10', text: 'wontfix' }];
function matchCustom(params, data) {
// If there are no search terms, return all of the data
if ($.trim(params.term) === '') {
return data;
}
// Do not display the item if there is no 'text' property
if (typeof data.text === 'undefined') {
return null;
}
// search by value
if (data.text.indexOf(params.term) > -1) {
return data;
}
// search by id
if (data.id.indexOf(params.term) > -1) {
return data;
}
// Return `null` if the term should not be displayed
return null;
}
$(".js-example-data-array").select2({
data: data,
matcher: matchCustom
});
});
.js-example-data-array {
width: 200px;
}
<select class="js-example-data-array"></select>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | pirelly |
Solution 2 | Ferry Kranenburg |
Solution 3 | Gleb Kemarsky |