Member-only story

How to Implement a Search Bar with Suggestions in JavaScript and HTML

Nexan
2 min readFeb 9, 2023

--

Photo by Maros Misove on Unsplash

As a web developer, you may have come across the need to implement a search bar in your application. One common requirement is to display suggestions as the user types into the search bar, allowing them to quickly find what they are looking for. In this article, I will show you how to create a search bar with suggestions using JavaScript and HTML.

To get started, we will create an array of products that the user can search for.

const products = ["Apple", "Banana", "Carrot", "Durian", "Eggplant"];

Next, we will create a function that will update the search suggestion list dynamically as the user types in the search bar.

function showSuggestions(str) {
let productList = document.getElementById("productList");
productList.innerHTML = "";

for (let i = 0; i < products.length; i++) {
if (products[i].toLowerCase().includes(str.toLowerCase())) {
let product = document.createElement("div");
product.innerHTML = products[i];
product.addEventListener("click", function() {
window.location.href = "product.html/" + products[i];
});
productList.appendChild(product);
}
}
}

In this function, we start by setting the innerHTML of the search suggestion list to an empty string. This is to…

--

--

Nexan
Nexan

Written by Nexan

We love to play and make games

No responses yet