I have a select box with some options in it and a input box. I have to filter the values of select box on the basis of the keyword entered in the text box.
JavaScript
function filter() {
var keyword = document.getElementById("search").value;
var select = document.getElementById("select");
for (var i = 0; i < select.length; i++) {
var txt = select.options[i].text;
if (txt.substring(0, keyword.length).toLowerCase() !== keyword.toLowerCase() && keyword.trim() !== "") {
select.options[i].style.display = 'none';
} else {
select.options[i].style.display = 'list-item';
}
}
}
HTML
<div>
<div>
<input type="text" id="search" name="search" style="margin: 10px;width: 165px;" onkeyup="filter()">
</div>
<div>
<select id="select" size="10" style="margin: 10px; width: 165px;height: 170px;">
<option>Cupcake</option>
<option>Cunut</option>
<option>Eclair</option>
<option>Froyo</option>
<option>Gingerbread</option>
<option>Honeycomb</option>
<option>Ice Cream Sandwich</option>
<option>Jelly Bean</option>
<option>KitKat</option>
<option>Lollipop</option>
<option>Marshmallow</option>
<option>Nougat</option>
</select>
</div>
</div>
Is this the right way for this task?
Here is the working code for the scenario.