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.
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:
In the HTML portion of the code, we define the visual elements of the dropdown.
dropdown-item
class and set the display
property to block
, so that the dropdown items appear below one another.button
element to act as the toggle for our dropdown.<input>
tag and the dropdown items.In the JavaScript portion of the code, we define the behavior of a typical dropdown.
filterDropDown()
function that takes the toggle button, the dropdown container, the input filter field, and a list of items.<a>
element for each item in the list. We set this element's href
attribute 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.onclick
event. The display property of the dropdown container is toggled between 'none'
and 'hidden'
.filterDropDown()
function we just defined. We pass the toggle button, the dropdown container, the input element, and the list of devices as parameters.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.
We add the filter logic in the JavaScript section of the code. The explanation for these lines is as follows:
input
event. The function executes whenever users type something in the input element.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