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.
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.
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!
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
).
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:
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.