Search/Filter Data in HTML Table using JavaScript
In this article, you will discover how to filter data in HTML table with JavaScript. The filter functionality allows you to filter data by category, and you can easily customize it to filter data by any other entity.
This is a follow-up to our previous article on how to fetch data from an API using the javascript fetch() method and display it in an HTML table. If you are unfamiliar with the fetch API and async/await, you may want to review this fetch API article first.
Let’s get started 🙂
Setting Up Your Project
To get started, create a new project folder on your computer. Inside this folder, create an index.html file and a js folder. Within the js folder, create a file named script.js. The index.html file will contain the HTML structure, while the script.js file will include the functions to fetch and filter the data.
This setup will help you organize your code and keep the project structured. Let’s dive into the details of each step of how to create a filter table with JavaScript.
Here is the JavaScript code you need to write in the script.js
file:
async function getData() {
let api = 'https://dummyjson.com/products';
let apiDataResponse = await fetch(api);
let data = await apiDataResponse.json();
let prod = data.products;
return {
products: prod
}
}
The getData
function is an asynchronous function that fetches data from the specified API and returns it as an object. It utilises async
and await
to handle the asynchronous operations.
let displayData = () => {
getData().then(result => {
let rows = '';
let tbody = document.getElementById('myTable');
let prod = result.products;
for (let i = 0; i < prod.length; i++) {
rows += `<tr>
<td><img src="${prod[i].thumbnail}" width="200px" height="150px" alt="img"/></td>
<td>${prod[i].title}</td>
<td>${prod[i].brand}</td>
<td>${prod[i].category}</td>
<td>${prod[i].description}</td>
<td>${prod[i].price}</td>
</tr>`;
}
tbody.innerHTML = rows;
});
}
displayData();
The displayData
function retrieves the product data and displays it in an HTML table by dynamically generating the rows.
How to Filter data in HTML table with javascript by product category
Now, I’m going to create a function filterByCategory
. This function filters the products by the category you will enter.
let filterByCategory = () => {
getData().then(result => {
let rows = '';
let tbody = document.getElementById('myTable');
let val = document.getElementById('productCategory').value.toLowerCase();
let prod = result.products;
for (let i = 0; i < prod.length; i++) {
if (prod[i].category.toLowerCase() === val) {
rows += `<tr>
<td><img src="${prod[i].thumbnail}" width="200px" height="150px" alt="img"/></td>
<td>${prod[i].title}</td>
<td>${prod[i].brand}</td>
<td>${prod[i].category}</td>
<td>${prod[i].description}</td>
<td>${prod[i].price}</td>
</tr>`;
}
}
tbody.innerHTML = rows.length ? rows : `<h3 style="color:red; margin-left:20px;">No record found for this category</h3>`;
});
}
The filterByCategory
function allows users to filter the products based on the entered category. It updates the table to only show products that match the specified category. This dummy data APi has four product categories: beauty, fragrances, groceries, and furniture.
HTML Structure
Here is the HTML code you need to write in the index.html
file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<div class="container mt-3">
<h2>Products Table</h2>
<p>Filter goods by product category</p>
<div class="row no-gutters">
<div class="col">
<input class="form-control" type="text" id="productCategory" placeholder="Filter by category">
</div>
<div class="col">
<button type="button" class="btn1 btn btn-primary" name="button" onclick="filterByCategory()"><i class="fa fa-search"></i></button>
</div>
</div>
</div>
<br>
<table class="table table-bordered">
<thead>
<tr>
<th>Thumbnail</th>
<th>Product Title</th>
<th>Brand</th>
<th>Category</th>
<th>Description</th>
<th>Price</th>
</tr>
</thead>
<tbody id="myTable">
</tbody>
</table>
</div>
</body>
<script type="text/javascript" src="js/script.js">
</script>
</html>
Final Result
How do I create a filter table with JavaScript?
To create a filter table with JavaScript, follow these steps:
– Set Up Your HTML: Create a table structure in your HTML with a <thead>
for headers and a <tbody>
for data rows. Include an input field for users to enter filter criteria and a button to trigger the filter.
– Fetch Data: Use JavaScript’s Fetch API to retrieve data from a server or API. Process this data and populate your table dynamically.
– Implement Filtering Logic: Write a JavaScript function that filters the table data based on user input. For example, if filtering by category, compare each row’s category with the input value and display matching rows.
–Update the Table: After filtering, update the table’s <tbody>
to show only the rows that meet the criteria or display a message if no matches are found.
For a practical example, check the detailed guide in our article on filtering data in an HTML table using JavaScript.
How to use JavaScript to search for specific data in a table?
To search for specific data in a table using JavaScript, you need to create a table with an input field for search criteria. Write a function that filters table rows based on user input and updates the table to show only matching rows. For a comprehensive guide on how to filter data in HTML table with JavaScript, refer to our detailed tutorial which walks you through the entire process.
Conclusion
This is the easiest method for filtering data, though it’s not the most optimal approach. There are plenty of other techniques you might explore, so I’ll leave it to you to experiment. Try to minimize redundancy and optimize the function.😀
Thank you for reading! If you found this article helpful and want to see more, don’t forget to follow for future updates. If you have any specific requests with a programming task, feel free to reach out to me.
I look forward to connecting with you!