Get selectize.js to display only options that begin with the user's input

Using selectize.js, my current setup looks like this:

https://i.sstatic.net/EqhF8.png

Instead of only showing words that start with 'arm', it displays words or options containing 'arm' as a substring elsewhere.

I want to modify the function to display only words or options that begin with 'arm'.

Despite consulting the usage documentation at https://github.com/selectize/selectize.js/blob/master/docs/usage.md, I couldn't find a solution. Does anyone have any ideas?

Answer №1

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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to establish a header in the login route that allows the browser to remember the user's login status?

I have successfully implemented a user login backend and everything seems to be working fine. However, when I try to access a user detail after logging in, I am faced with an authorization issue preventing me from exploring other routes. How can I store th ...

Is the jQuery ajax .done() function being triggered prematurely?

Struggling with a problem here. I'm dealing with this code (simplified): var initializeZasilkovna = function () { // Initialize object window.packetery.initialize(); }; // Check if the object doesn't exist if (!window.packetery) { // It ...

"Learn how to deactivate the submit button while the form is being processed and reactivate it once the process is

I have been searching for solutions to this issue, but none seem to address my specific concern. Here is the HTML in question: <form action=".."> <input type="submit" value="download" /> </form> After submitting the form, it takes a ...

How can I create an input field that only reveals something when a specific code is entered?

I am currently developing a website using HTML, and I would like to create an admin section that requires a password input in order to access. After consulting resources on w3schools, I attempted the following code: <button onclick="checkPassword()" i ...

Exploring the Dynamic Routing Features of Next.js

After diving into Next.js, I found the learning curve to be manageable since React was already familiar territory for me. Currently, my focus is on implementing dynamic routing in my application - Starting with my live/index.js file - (Where I utilize ge ...

No code is appearing on the page, just a blank space

Whenever I visit this page on the web, the screen shows up as empty and I've encountered similar issues with other JavaScript pages that I've created. This makes me wonder if there might be a missing piece of code or something else causing the pr ...

Storing an Excel file with JavaScript: A comprehensive guide

I've been struggling to save an Excel file using Javascript, but I'm facing compatibility issues with different browsers. I initially tried using BASE64 along with data URL, which worked well in Chrome and Firefox but failed in IE and Safari. ne ...

Quick fix for obtaining only one response

I'm facing a dilemma where I need to redirect the user to the dashboard page after they log in, but also send their JSON details to my client-side JavaScript. While I know that there can only be one res.send/end/json in a response and dynamic data can ...

Customizing the items-per-page selection in the v-data-table component with Vuetify

I have a data table component footer with a select option that I want to update the values of. Can anyone guide me on how to achieve this? Is there a way to customize the numbers in the select option? https://i.sstatic.net/I5HCA.png ...

How can I show a legend entry for every column in Amcharts?

Take a look at this code snippet: http://jsfiddle.net/ouLed1fp/ How can I create a legend entry for each column in the chart? Also, is there a way to display the column names next to them, providing a clear legend? <div id="chartdiv" style="width: 10 ...

Rendering React Js component occurs just once following a state update

My journey with ReactJS is just beginning, and I'm facing an unusual issue which might be due to my unconventional implementation approach. Previously, everything was working smoothly. However, when I tried to introduce new features, things started g ...

Encounter a problem while installing node modules

I am facing an issue with my test directory which contains a package.json file: { "name": "test", "version": "0.0.1", "dependencies": { "hem": "~0.1.6", } } Upon trying to run node install, I encounter the following error: module.js:337 ...

Unable to attach an onClick event handler to <TableRowColumn> element using Material-UI in React

In the past, I had a feature that allowed me to change the color of the text from red to green by clicking on a table cell. After introducing Material-UI in my React app and replacing the <td> tags with <TableRowColumn> tags, I noticed that th ...

Generate a library using Vue CLI from a component and then import it into your project

When using vue-cli to build my lib, I run the following command: "build": "vue-cli-service build --target lib --name myLib ./src/component.vue" After the build, how can I import my component from the dist folder? Importing from path-to-myLib/src/compone ...

Manipulate the 'i' variable within a for loop using JavaScript, JQuery, and JSON to modify an attribute

I have 4 picture locations saved in a JSON file named img0, img1, img2, and img3. By using an AJAX call (getJSON), I retrieve the data from the file and then assign them to the "src" attribute of the images on my webpage. Everything works fine with this c ...

The issue of execution order in JavaScript Recursion with promises

In the process of developing a method for creating markup to be used in a web app's off-canvas navigation. One of the challenges I am facing is making an asynchronous callback to another service that provides children nodes for the parent menu node (r ...

Capture data from a Telegram bot and store it in a Google Sheet

I am trying to use a spreadsheet through a Telegram bot as a TODO list so that when I input something on my phone, it is saved in the spreadsheet. (I'm following this tutorial https://www.youtube.com/watch?v=XoTpdxbkGGk, which seems accurate with Goog ...

React web app experiencing an issue with MUI Drawer opening flawlessly but failing to close

Recently, I encountered an issue with my React app. I have a Navbar component that displays a Sidebar component when the screen is small, using Material UI for the Drawer functionality. The problem arises when clicking the hamburger icon to open the drawe ...

How can one effectively manage asynchronous behavior on the client side of a Meteor application?

My focus is on Meteor. I want to connect with the Facebook API through Meteor's HTTP in order to show images on Meteor's client side. I've come across suggestions like Fiber Futures, storing data in Sessions, and triggering a synchronous se ...

Display solely the initial row in the tbody segment of a table. Is there a method to obscure subsequent 1st rows?

The initial row of each tbody acts as the row header, containing the column names. Subsequent rows in each tbody are unnecessary and should be hidden. Classes utilized: toprowHeader = first row containing column names recordsRow = holds additional recor ...