HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptMinor

Filter options of select box using input box value

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
optionsvalueinputfilterusingselectbox

Problem

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


    
        
    
    
        
            Cupcake
            Cunut
            Eclair
            Froyo
            Gingerbread
            Honeycomb
            Ice Cream Sandwich
            Jelly Bean
            KitKat
            Lollipop
            Marshmallow
            Nougat
        
    


Is this the right way for this task?

Here is the working code for the scenario.

Solution

A good attempt I must say, but there are other ways to achieve this.

Just so you know, select.option returns an optionCollection which can be cast to an array using Array.from(select.options).

Based on this, you can utilise the filter pre-defined function for an array object

var optionCollection = Array.from(select.options).filter(x => x.text.toLowerCase().startsWith(keyword.toLowerCase()))


this will get rid of the for..loopyou had. In addition, using filter function doesn't change the array but returns a new array with the filtered content.

The result from this can be used to replace the html of the select element i.e

$("#select").html(optionCollection)



Note: the above is JQuery

To effectively use the JQuery, you can embed this in a ternary operator

optionCollection.length > 0 ? $("#select").html(b) : $("#select").html(realCollection);


Note: the realCollection will be the initial select options collection.

I hope this helps

Code Snippets

var optionCollection = Array.from(select.options).filter(x => x.text.toLowerCase().startsWith(keyword.toLowerCase()))
$("#select").html(optionCollection)
optionCollection.length > 0 ? $("#select").html(b) : $("#select").html(realCollection);

Context

StackExchange Code Review Q#140420, answer score: 4

Revisions (0)

No revisions yet.