JavaScript ES6 snippet to filter the options in a select list.
[topads][/topads]
The HTML
We only have two elements in the HTML, an input and a select multiple elements.
<div> <input type="text" placeholder="Filter by car name" autocomplete="off" /> <br /> <select multiple> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="mercedes">Mercedes</option> <option value="audi">Audi</option> <option value="volkswagen">Volkswagen</option> <option value="toyota">Toyota</option> <option value="ford">Ford</option> <option value="subaru">Subaru</option> <option value="mini">Mini</option> </select> </div>
The JavaScript
First we get the select and input elements, then from the select element we get the optionss.
const select = document.querySelectorAll('select'); const input = document.querySelector('input'); const options = Array.from(select[0].options);
We write a function that will find a match in a given list of options returning an array of the items that matched the input word.
function findMatches(search, options) { return options.filter((option) => { const regex = new RegExp(search, "gi"); return option.text.match(regex); }); }
[signupform][/signupform]
Then write a function that clears the options, matches the word typed in the input field and appends this new array (returned from findMatches) to the select element.
function filterOptions() { options.forEach((option) => { option.remove(); option.selected = false; }); const matchArray = findMatches(this.value, options); select[0].append(...matchArray); }
Finally we add two event listeners to the input field, change and keyup that will call the filterOptions function.
input.addEventListener('change', filterOptions); input.addEventListener('keyup', filterOptions);
Last but not least, we wrap everything in an IIFE so that this code will not conflict with any other code you we might have in the page.
(function() { ... })();
Full Code
(function() { const select = document.querySelectorAll('select'); const options = Array.from(select[0].options); const input = document.querySelector('input'); function findMatches (search, options) { return options.filter(option => { const regex = new RegExp(search, 'gi'); return option.text.match(regex); }); } function filterOptions () { options.forEach(option => { option.remove(); option.selected = false; }); const matchArray = findMatches(this.value, options); select[0].append(...matchArray); } input.addEventListener('change', filterOptions); input.addEventListener('keyup', filterOptions); })();
Live Demo
See the Pen Filter Select List Options (Typeahead) by Esau Silva (@esausilva) on CodePen.dark
Consider giving back by getting me a coffee (or a couple) by clicking the following button:
[bottomads][/bottomads]
Not working on IE
In this snippet I make use of several ES6 features that are not supported by IE.
– Spread Syntax
– Array.from()
– Arrow Functions