2
votes

I am using selectize.js. Currently it looks like this:

enter image description here

It shows not only words that start with 'arm', but also words (or options) that contain 'arm' as a substring somewhere else.

I would like to force the function to show only those words (or options) that start with 'arm'.

I checked the usage documentation at https://github.com/selectize/selectize.js/blob/master/docs/usage.md but was not able to figure out how to solve this.

Does anybody have any ideas?

1
You may be able to do it with the score setting (you will find it in the docs at the link you provided in your question).benvc

1 Answers

3
votes

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);
  return function(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) {
    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>