Skip to content

Instantly share code, notes, and snippets.

@nkokkos
Last active May 23, 2021 17:58
Show Gist options
  • Save nkokkos/0287d3ba19c42bc0b6e18377b959a009 to your computer and use it in GitHub Desktop.
Save nkokkos/0287d3ba19c42bc0b6e18377b959a009 to your computer and use it in GitHub Desktop.
Filter Select List Box with ES6
/* Stolen from here: https://esausilva.com/2017/02/21/filter-select-list-options-typeahead-in-javascript-es6/ */
/* Added document.getElementByID instead of querySelectorAll
<html>
<head>
<style>
div {
width: 280px;
margin: 10 auto;
}
input {
font-size: 160%;
width: 280px;
}
select {
width: 280px;
margin-top: 15px;
font-size: 160%;
}
</style>
</head>
<body>
<div>
<input type="text" id="my_input" placeholder="Filter by name" autocomplete="off" />
<br />
<select id="my_list_with_id" size="16" 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>
<option value="687">Αλφα</option>
<option value="688">Βήτα</option>
<option value="689">Γαμα</option>
<option value="china1">亂</options>
<option value="china2">數</options>
<option value="china3">假</options>
<option value="china4">器</options>
</select>
</div>
</body>
<script type="text/javascript">
const my_select_element = document.getElementById('my_list_with_id');
const my_options = Array.from(my_select_element.options);
const my_input = document.getElementById('my_input');
function findMatches (search, options) {
return options.filter(option => {
const regex = new RegExp(search, 'gi');
return option.text.match(regex);
});
}
function filterOptions () {
my_options.forEach(option => {
option.remove();
option.selected = false;
});
const matchArray = findMatches(this.value, my_options);
console.log(this.value)
console.log(my_options)
console.log(matchArray)
my_select_element.append(...matchArray);
}
my_input.addEventListener('change', filterOptions);
my_input.addEventListener('keyup', filterOptions);
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment