Create a Search Filter using JavaScript

In this tutorial, we are going to build a search filter that can help us search and find specific records from a long list of records.

In a search filter, we basically put a search term into the search box and the filter shows us only those records which match the search term. Now, these records can be a list of products, users, inventory, or any other item.

Below is a demo of the search filter that we are going to develop:

  • Agra
  • Aligarh
  • Meerut
  • Raipur
  • Ranchi
  • Delhi
  • Kanpur
  • Mumbai

And here is the JavaScript code with a working example:

Example:

let ul = document.querySelector('#cont');

function filter(inputTxt) {
    inputTxt = inputTxt.toLowerCase();

    // Loop through each list item and hide those which aren't matching 
    for(let i = 0; i < ul.children.length; i++){
        if(!ul.children[i].innerText.toLowerCase().includes(inputTxt)){
            ul.children[i].style.display = 'none';
        }else{
            ul.children[i].style.display = '';
        }

    }
}

Code Explanation:

The search filtration is done in the below three steps:

  1. As soon as the user starts typing in the input box, the custom filter() function gets fired. It then passes the value of the search term as an argument.
  2. To make the search case insensitive, we first convert the search term to lowercase.
  3. In the third step, we loop through each list item and check if the search term is present in the current list item using the built-in includes() function. If it is not in the list item, we simply remove the list item by applying display: none; on it. Otherwise, we keep the list item as it is. That's all.

Thanks for reading.

Note: If you want to make the search case-sensitive, you have to remove the toLowerCase() function.

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.