choices-js filtering select options that only use numbers and blanks

256 Views Asked by At

I'm tring to enhance the following select field with choices-js:

<select class="form-select" id="telephone" aria-label="Default select example">
  <option value="0901-68738">0901-68738</option>
  <option value="0904-687 11">0904-687 11</option>
  <option value="0906-68712">0906-68712</option>
</select>

The select is initialised with

const element = document.querySelector('#telephone');
const choices = new Choices(element);

My Problem is using the search does lead to unexpected results.

A search for "0906" does not hide the options that not have the search term

enter image description here

The same for " 11"

enter image description here

Where "738" correctly works

enter image description here

Question: Which options are needed to

  • respect the search where the value starts with a number like 0906
  • respect the search where the value ends with a number and a blank like " 11"
  • Hide other options in both cases as they do not inlude the search terms

Fiddle: https://codepen.io/t-book/pen/BavdjKO

1

There are 1 best solutions below

1
Charles On

I read through their README and looked through the code itself but I'm not seeing an option to only return exact but partial matches. It seems the purpose of using this library is to filter choices based on a scoring system. Filtering based on another method might undermine the purpose of its design.

A good alternative that matches your needs would be an input and datalist, like so:

<input type="number" list="telephone_list"/>
<datalist id="telephone_list">
    <option value="0901-68738"></option>
    <option value="0904-687 11"></option>
    <option value="0906-68712"></option>
</datalist>

Update: Thanks to Crezzur for pointing out Choices-js uses Fuse.js for its search. The threshold property under the fuseOptions property of the Choices initialization method is what you're looking for. A value of 0.1 seems to provide the behavior you're after; see below for the updated Choices call in your Fiddle:

const choices = new Choices(element, {
  searchChoices: true,
  valueComparer: (a, b) => value.trim() === b.trim(),
  fuseOptions: {
    threshold: 0.1
  },
});