To sort items and loop through the entire list based on relevance, you can utilize the score
property. Each item is assigned a score of 1 if it's highly relevant, 0 if it doesn't match, and thus excluded from the list. With this understanding, we can create a customized function.
Upon entering a new character, the score function is invoked. It then evaluates each item using the following structure:
item = {
text: 'Armband',
value: 'Armband',
}
For evaluation, we take the lowercase version of item.text
, compare it with the lowercase search
value. If item.text
begins with the search term, return 1 indicating inclusion; otherwise, return 0 for exclusion. The complete score
function is outlined below.
score: function(search) {
var score = this.getScoreFunction(search);
return function(item) {
return item.text
.toLowerCase()
.startsWith(search.toLowerCase()) ? 1 : 0;
};
},
An example showcasing this functionality in action is provided below.
if (!String.prototype.startsWith) {
String.prototype.startsWith = function(search, pos) {
return this.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
};
}
$('.select').selectize({
placeholder: 'Maak een keuze',
openOnFocus: true,
items: [''],
score: function(search) {
var score = this.getScoreFunction(search);
return function(item) {
return item.text
.toLowerCase()
.startsWith(search.toLowerCase()) ? 1 : 0;
};
},
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.4/css/selectize.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.4/js/standalone/selectize.min.js">
</script>
<select class="select" selected="">
<option>Arm</option>
<option>Armoede</option>
<option>Armband</option>
<option>Edeldarm</option>
<option>Warmbloedig</option>
<option>Opgewarmd</option>
</select>