Reputation: 2462
Is there a way to search for any matched letters in select2?
For example, if I have the following options:
<option value="MANGO">MANGO</option>
<option value="ORANGE">ORANGE</option>
<option value="APPLE">APPLE</option>
and if I type "mngo", is there a way to show "MANGO" option in the search result?
Upvotes: 3
Views: 1121
Reputation: 10922
The regex is clear, it's adding a .*
between each character and before and after all characters. You can change that wildcard as you please.
I tried to be the less verbose possible, was tricky and fun doing this.
$('#select2').select2({
matcher: function(term, text) {
// If search is empty we return everything
if ($.trim(term.term) === '') return text;
// Compose the regex
var regex_text = '.*';
regex_text += (term.term).split('').join('.*');
regex_text += '.*'
// Case insensitive
var regex = new RegExp(regex_text, "i");
// If no match is found we return nothing
if (!regex.test(text.text)) {
return null;
}
// Else we return everything that is matching
return text;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<select id="select2" style="width:100%;">
<option value="MANGO">MANGO</option>
<option value="ORANGE">ORANGE</option>
<option value="APPLE">APPLE</option>
</select>
Upvotes: 4