Build a Searchbar Using JavaScript in Five Steps

Introduction

Problem Solving

Step 1: Create the Interface

First, define a <div> and place a title, a search form, and a list for displaying search results inside it.

<div>
<!-- Title -->
<h1>Book Finder</h1>
<!-- Search Form -->
<form data-bookfinder-form>
<input name="search" type="text" placeholder="Please enter search content..." />
<button type="submit">Submit</button>
</form>
<!-- Search Results -->
<ul data-books></ul>
</div>

Step 2: Define the Data

First, define a piece of data. Here, we define an array containing several book-related objects. The data structure can be defined as you wish; it’s fine to define your own or fetch third-party data.

const books = [
{
name: 'A Tale of Two Cities',
author: 'Charles Dickens',
},
{
name: 'The Boy Scouts',
author: 'Baden-Powell',
},
{
name: 'The Lord of the Rings',
author: 'J.R.R. Tolkien',
},
];

Step 3: Render Data on the Screen

With the data in hand, we can focus on how to present the existing data on the screen. This is split into two functions: one for “generating the HTML to display the data on the screen” and another for “rendering the results on the screen.” I prefer to break down the functionality of the code into the smallest parts, making it easier to read, maintain, and test. Now, you should see the data we defined earlier on the screen!

function renderBooks(targetHTML) {
const bookList = document.querySelector('[data-books]');
bookList.innerHTML = targetHTML;
}
function generateBookHTML(targetBooks) {
return targetBooks
.map((book) => {
return `<li class="bookList__item">${book.name} - <span class="bookList__author">${book.author}</span></li>`;
})
.join('');
}

Step 4: Listen to the Form

We previously defined the data-bookfinder-form attribute. Here, we can use querySelector to select this element and listen for the submit event. Whenever the user presses the submit button, we can retrieve the value entered by the user (e.target.search.value).

document.querySelector('[data-bookfinder-form]').addEventListener('submit', (e) => {
e.preventDefault();
renderBooks(generateBookHTML(booksFilter(e.target.search.value)));
});

Step 5: Filtering Function

Now the key is how to filter the data with the booksFilter function. In fact, it’s quite simple; we just need to compare the submitted value from the form with each existing piece of data. If there is a match, we return that piece of data, which can be written in code like this:

function booksFilter(targetBook, allBooks = books) {
return allBooks.filter((book) => {
return book.name.includes(targetBook);
});
}

Conclusion

From this simple exercise, we achieved a common functionality using existing methods provided by JavaScript. Below is the complete code, which you can try out on CodePen:

See the Pen Book-Finder by Riceball ( @riecball) on CodePen.