how to add search filter in dropdown select html javascript

How to Add a Search Filter in Dropdown Select HTML JavaScript

If you have a long list of options in a dropdown select menu, it can be difficult for users to find the option they are looking for. A search filter can make this process much easier. Here is how to add a search filter in dropdown select using HTML and JavaScript.

Step 1: HTML Markup

Create a div element that will contain the dropdown select and the search filter input field. Give the div an id so that you can reference it in your JavaScript code.

<div id="myDropdown">
  <input type="text" placeholder="Search.." id="myInput">
  <select id="mySelect">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    <option value="3">Option 3</option>
    <option value="4">Option 4</option>
    <option value="5">Option 5</option>
    <option value="6">Option 6</option>
    <option value="7">Option 7</option>
    <option value="8">Option 8</option>
    <option value="9">Option 9</option>
    <option value="10">Option 10</option>
  </select>
</div>

Step 2: JavaScript Code

Now, you need to write the JavaScript code that will add the search filter functionality to the dropdown select. Here is how to do it:

<script>
  // Get the div that contains the dropdown select and the search filter input field
  var myDropdown = document.getElementById("myDropdown");

  // Get the input element that will be used for searching
  var myInput = myDropdown.querySelector("#myInput");

  // Get the select element
  var mySelect = myDropdown.querySelector("#mySelect");

  // Loop through each option in the select element and hide those that do not match the search query
  function filterOptions() {
    var filter = myInput.value.toUpperCase();
    var options = mySelect.getElementsByTagName("option");
    for (var i = 0; i < options.length; i++) {
      var txtValue = options[i].textContent || options[i].innerText;
      if (txtValue.toUpperCase().indexOf(filter) > -1) {
        options[i].style.display = "";
      } else {
        options[i].style.display = "none";
      }
    }
  }

  // Add an event listener to the input element that will call the filterOptions function every time the user types something in the search field
  myInput.addEventListener("keyup", filterOptions);
</script>

This JavaScript code will add a search filter to the dropdown select. When the user types something in the search field, it will loop through each option in the select element and hide those that do not match the search query.

You can modify this code to suit your specific needs. For example, you can change the placeholder text for the search field or modify the styling of the dropdown select to make it look more appealing.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe