Skip to content Skip to sidebar Skip to footer

Force Selectize.js Only To Show Options That Start With User Input

I am using selectize.js. Currently it looks like this: It shows not only words that start with 'arm', but also words (or options) that contain 'arm' as a substring somewhere else.

Solution 1:

You can use the score property which loops through the entire list and sorts items. 1 being the most relevant one, 0 is considered as not matching, and the item is excluded. Knowing this we can write our own function :)

The score function is called each time a new character is entered. The inner function of score then checks each item, here's the structure of an item.

item = {
  text: 'Armband',
  value: 'Armband',
}

Knowing this we take item.text, make all letters lowercase (remove .toLowerCase() if you don't want this) and compare it with the value search(also lowercase). When item.text starts with the value in search, then return 1 - item should be included - else 0 and the item is excluded from the list. Here's the entire function for score.

score: function(search) {
  var score = this.getScoreFunction(search);
  returnfunction(item) {
    return item.text
      .toLowerCase()
      .startsWith(search.toLowerCase()) ? 1 : 0;
  };
},

Below is a working example to see it in action.

if (!String.prototype.startsWith) {
  String.prototype.startsWith = function(search, pos) {
    returnthis.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);
    returnfunction(item) {
      return item.text
        .toLowerCase()
        .startsWith(search.toLowerCase()) ? 1 : 0;
    };
  },
});
<linkrel="stylesheet"href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"><linkrel="stylesheet"type="text/css"href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.4/css/selectize.min.css"><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script><scriptsrc="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script><scripttype="text/javascript"src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.4/js/standalone/selectize.min.js"></script><selectclass="select"selected=""><option>Arm</option><option>Armoede</option><option>Armband</option><option>Edeldarm</option><option>Warmbloedig</option><option>Opgewarmd</option></select>

Post a Comment for "Force Selectize.js Only To Show Options That Start With User Input"