How to make a search bar (JavaScript)

Search functionality is a crucial feature for many websites, especially those that have a lot of content or data. A search app allows users to quickly find what they're looking for on your site, without having to manually scan through pages or scroll through a long list.

Getting Started

First, create an HTML file with a list of values that you want to search through. For this tutorial, we'll create a simple list of countries:

<center>
  <input type="text" id="searchInput" placeholder="Search...">
    <ul>
      <li class="searchable">Australia</li>
      <li class="searchable">Brazil</li>
      <li class="searchable">Canada</li>
      <li class="searchable">Denmark</li>
      <li class="searchable">Egypt</li>
      <li class="searchable">France</li>
      <li class="searchable">Germany</li>
      <li class="searchable">Hungary</li>
      <li class="searchable">India</li>
      <li class="searchable">Japan</li>
   </ul>
</center>

Next, let's create the JavaScript code that will handle the search functionality.

In our app.js file, we'll create a function called searchFunction() that will be called every time the user types something into the search bar. This function will filter out the values on the page that don't match the user's input.

function searchFunction() {
    // Get the input value from the search bar
    let input = document.getElementById("searchInput").value.toLowerCase();

    // Get all the values on the page that need to be searched
    let values = document.getElementsByClassName("searchable");

    // Loop through the values and hide the ones that don't match the search input
    for (let i = 0; i < values.length; i++) {
      let value = values[i].textContent.toLowerCase();
      if (value.indexOf(input) > -1) {
        values[i].style.display = "";
      } else {
        values[i].style.display = "none";
      }
    }
  }

  let searchInput = document.getElementById("searchInput");
  searchInput.addEventListener("keyup", searchFunction);

This function first gets the value of the search bar and converts it to lowercase. Then it gets all the elements on the page that need to be searched (in this example, we're assuming they all have a class of "searchable"). It loops through each value and checks if it contains the search input. If it does, it displays the value; if not, it hides the value.

Finally, we add an event listener to the search bar input element that calls the searchFunction() every time the user types something into the search bar.

0
Subscribe to my newsletter

Read articles from Devashish Jadhav directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Devashish Jadhav
Devashish Jadhav