Simple Async Search Bar with JavaScript

Rachel Hawa
Nov 2, 2019 · 2 min read
Image for post
Image for post

This is a quick guide on how to set up a search bar. I’ll be using a list of the 50 states, rendered as an unordered list as an example. However, you can use this same search for anything or any part of an application by changing the variables and tags.

Image for post
Image for post

First take a look at the sample HTML.

<ul id="stateList">
<li>New Hampshire</li>
<li>New Jersey</li>
<li>New Mexico</li>
<li>New York</li>
<li>North Carolina</li>
<li>North Dakota</li>
<li>Rhode Island</li>
<li>South Carolina</li>
<li>South Dakota</li>
<li>West Virginia</li>

The first thing to add for a search bar is… a search bar.

<input type="text" placeholder="Search">

We need to add an id to this, so that we can identify it with JavaScript.

<input type="text" id="myInput" placeholder="Search">

We also need to add an event listener and call our JavaScript function (coming soon!) There are a few that would work — I’m going to use onKeyUp, which is triggered after the user types something.

<input type="text" id="myInput" onkeyup="mySearchFunction()" placeholder="Search">

Now let’s put together the JavaScript. In the HTML for our search bar, a function is being called — let’s build that. To get this up and working, here are the steps to code out:

  1. Declare variables, the user input (what’s being typed in the search box, a filter (so we can ignore case), the list, each item in the list.
  2. Treat our list like an array — using the indices to iterate over each item, comparing the inner text or inner html with the input.
  3. Display matching list items, or nothing if no match.
function mySearchFunction() {
var input, filter, ul, li, item, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
ul = document.getElementById("stateList");
li = ul.getElementsByTagName("li"); for (i = 0; i < li.length; i++) {
item = li[i];
txtValue = item.textContent || item.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";

Here’s a CodePen to see this in action.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store