Filtering a drop down list using Javascript with Asp.Net

February 05, 2023

In this post, I’ll cover creating a filter for an Asp.Net drop down list. Let’s take the following list as an example:

@Html.DropDownListFor(a => a.MySelection, 
    new SelectList(Model.AvailableOptions, "Id", "DisplayDescription"), null, 
    new { @class = "select-list-style" }); 

What we want to do here is to add a textbox to this page that allows filtering of these options. Let’s add a basic textbox then:

<input type="text" placeholder="Search.." id="searchInput" 
            onkeyup="filterFunction()" class="form-control" />    

If you run this now, you’ll see a free entry textbox, but sadly it will do nothing. However, all we now need to do is write the filterFunction():

function filterFunction() {
    const input = document.getElementById("searchInput");
    const filter = input.value.toUpperCase();
    const mySelectedList = document.getElementById("MySelection");          
    for (i = 0; i < mySelectedList.length; i++) {
        const eachSelectedItem = mySelectedList[i];
        const eachValue = eachSelectedItem.textContent || eachSelectedItem.innerText;
        if (eachValue.toUpperCase().indexOf(filter) > -1) {
   = "";
        } else {
   = "none";

All we’re really doing here is iterating through each element in the options list of the drop down and, where there’s no match, hiding that option.

Profile picture

A blog about one man's journey through code… and some pictures of the Peak District

© Paul Michaels 2023