Filter options of select box using input box value 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 &lt; select.length; i++) {
        var txt = select.options[i].text;
        if (txt.substring(0, keyword.length).toLowerCase() !== keyword.toLowerCase() &amp;&amp; keyword.trim() !== "") {
            select.options[i].style.display = 'none';
        } else {
            select.options[i].style.display = 'list-item';
        }
    }
}


HTML

&lt;div&gt;
    &lt;div&gt;
        &lt;input type="text" id="search" name="search" style="margin: 10px;width: 165px;" onkeyup="filter()"&gt;
    &lt;/div&gt;
    &lt;div&gt;
        &lt;select id="select" size="10" style="margin: 10px; width: 165px;height: 170px;"&gt;
            &lt;option&gt;Cupcake&lt;/option&gt;
            &lt;option&gt;Cunut&lt;/option&gt;
            &lt;option&gt;Eclair&lt;/option&gt;
            &lt;option&gt;Froyo&lt;/option&gt;
            &lt;option&gt;Gingerbread&lt;/option&gt;
            &lt;option&gt;Honeycomb&lt;/option&gt;
            &lt;option&gt;Ice Cream Sandwich&lt;/option&gt;
            &lt;option&gt;Jelly Bean&lt;/option&gt;
            &lt;option&gt;KitKat&lt;/option&gt;
            &lt;option&gt;Lollipop&lt;/option&gt;
            &lt;option&gt;Marshmallow&lt;/option&gt;
            &lt;option&gt;Nougat&lt;/option&gt;
        &lt;/select&gt;
    &lt;/div&gt;
&lt;/div&gt;


Is this the right way for this task?

Here is the working code for the scenario.
I would start by moving the search term into the function definition, to save having to look up the DOM element. So I would change in the HTML 

 &lt;input type="text" id="search" name="search" style="margin: 10px;width: 165px;" onkeyup="filter(this.value)"&gt;


And then have function be defined with keyword as a parameter.

function filter(keyword) {
  ...
}


The other main change I would make is to use string.prototype.startsWith rather than substring checking, this is more explicit about what is trying to be done, and saves having logic to handle the empty string.

Also, rather than an If statement and then setting style.display, the display is set with either 'list-item' or 'none' with the ternary operator.

This leaves the function as 

function filter(keyword) {
    var select = document.getElementById("select");
    for (var i = 0; i &lt; select.length; i++) {
        var txt = select.options[i].text;
        var include = txt.toLowerCase().startsWith(keyword.toLowerCase());
        select.options[i].style.display = include ? 'list-item':'none';
    }
}


A further improvement you might want to look at may include moving the select element selection outside of this function to improve re-use.