This blog post will define the process of filtering the table in JavaScript.
How to Filter Table in JavaScript?
Let’s see an example explaining how to filter a table in JavaScript.
Example
First, create a search bar in an HTML document with the “onkeyup” property that call the “filterTableFunc()” when the key is released:
Create a table that stores employee data using the <table> tag, and assign an id “employeeData”:
<tr>
<th>Name</th>
<th>Email</th>
<th>Gender</th>
<th>Designation</th>
<th>Joining Date</th>
</tr>
<tr>
<td>John</td>
<td>john@gmail.com</td>
<td>Male</td>
<td>CPA</td>
<td>5/5/2020</td>
</tr>
<tr>
<td>Stephen</td>
<td>stephen@gmail.com</td>
<td>Male</td>
<td>HRM</td>
<td>21/10/2020</td>
</tr>
<tr>
<td>Mari</td>
<td>mari78@gmail.com</td>
<td>Female</td>
<td>HRM</td>
<td>16/05/2022</td>
</tr>
<tr>
<td>Rhonda</td>
<td>rhonda12@hotmail.com</td>
<td>Male</td>
<td>CFA</td>
<td>23/06/2022</td>
</tr>
</table>
After executing the HTML file, the output will look like this:
After that, let’s add functionality to the filter table. In a JavaScript script file or a tag, use the below code that will filter the table’s data based on search:
var filterResult = document.getElementById("search").value.toLowerCase();
var empTable = document.getElementById("employeeData");
var tr = empTable.getElementsByTagName("tr");
for (var i = 1; i < tr.length; i++) {
tr[i].style.display = "none";
const tdArray = tr[i].getElementsByTagName("td");
for (var j = 0; j -1) {
tr[i].style.display = "";
break;
}
}
}
}
In the above-given code:
- First, define a function “filterTableFunc()”.
- Access the search bar using its id “search” to get the entered value and convert it into a lowercase using the “toLowerCase()” method.
- Get a reference to the table where the filter operation will be performed using its id “employeeData”.
- Then, get the table rows using the “getElementsByTagName” method.
- Iterate through the table up to its length, get the data for each table entry, and check if the stored value of the table is equal to the searched value. If it is, then display it.
Output
The above output indicates that the filter operation has been successfully applied to the table.
Conclusion
A table can be filtered in JavaScript by iterating through the table data and returning the relevant data. This filtering is done through a function called upon a specific event. This approach will work in such a way that on identical data entered, the corresponding data from the table is fetched, regardless of the case sensitivity in the input text field. This post describes an approach that can be used to filter a table in JavaScript.