How to filter dropdowns in JavaScript
A dropdown is a collapsible list of options from which users can choose one. Often, dropdowns become lengthy and difficult to use. However, a filter can show only those options that users are interested in seeing.
We implement a simple text filter on a dropdown in the following example.
Step 1: Creating the dropdown
The first step is to create a button, a dropdown menu, and an input field. The button toggles the dropdown, and the input field filters the dropdown elements.
Note: The code examples use the following methods. We can click the method to learn about its use:
Explanation
In the HTML portion of the code, we define the visual elements of the dropdown.
- Line 4: We create a
dropdown-itemclass and set thedisplayproperty toblock, so that the dropdown items appear below one another. - Line 5: We create a
buttonelement to act as the toggle for our dropdown. - Lines 9–11: We create a container for the
<input>tag and the dropdown items.
In the JavaScript portion of the code, we define the behavior of a typical dropdown.
- Line 1: We create a list of dropdown items that we want users to see.
- Line 2: We define a
filterDropDown()function that takes the toggle button, the dropdown container, the input filter field, and a list of items. - Lines 5–11: We create an
<a>element for each item in the list. We set this element'shrefattribute to an arbitrary value, its class to the dropdown-item class, and its display value to the list item. Finally, we append it to the dropdown container element. - Lines 16–23: We add an event listener on the button for the
onclickevent. The display property of the dropdown container is toggled between'none'and'hidden'. - Lines 29–34: We call the
filterDropDown()function we just defined. We pass the toggle button, the dropdown container, the input element, and the list of devices as parameters.
Step 2: Adding the filter logic
So far, we have a working dropdown, but it does not filter options according to the input. Let's add in some code to do just that.
Explanation
We add the filter logic in the JavaScript section of the code. The explanation for these lines is as follows:
- Line 23: We add an event listener to the input element for the
inputevent. The function executes whenever users type something in the input element. - Line 24–26: The list of dropdown item elements is retrieved. If an empty list is retrieved, we exit the function.
- Line 27–32: We loop through each dropdown item and check if the displayed text includes the value from the input field. If it does, we display that item. Otherwise, we hide it.
- Line 28: We do the comparison using the
toUpperCase()method. This method converts all characters in the string to uppercase and lets us ignore case sensitivity for the filter.
Note: Optionally, to polish the look of the dropdown, we can apply a little CSS.
Free Resources