Filter Html table with JavaScript

In this post, we will learn how to filter records from table with the help of JavaScript.

Filter / Search in table with JavaScripit:

<html>
<head>Search in table</head>
<body>
<h2>My Students</h2>
<input type=”text” id=”txtSearch” onkeyup=”search()” placeholder=”Search” title=”Type Name Or Course”>
<hr/>
<table id=”studentRecords” border=”1″>
<tr>
<th style=”width:50%;”>Name</th>
<th style=”width:50%;”>Course</th>
</tr>
<tr>
<td>Tarun</td>
<td>Php</td>
</tr>
<tr>
<td>Amit</td>
<td>Java</td>
</tr>
<tr>
<td>Sumit</td>
<td>Basic</td>
</tr>
<tr>
<td>Ravi</td>
<td>Asp</td>
</tr>
<tr>
<td>Nitin</td>
<td>Basic</td>
</tr>
<tr>
<td>Deepak</td>
<td>Java</td>
</tr>
<tr>
<td>Atul</td>
<td>Asp</td>
</tr>
<tr>
<td>Albart</td>
<td>Java</td>
</tr>
</table>

<script>
function search() {
var searchText, filterTxt, stdTable, tr, td, a;
searchText = document.getElementById(“txtSearch”);
filterTxt = searchText.value.toUpperCase();
stdTable = document.getElementById(“studentRecords”);
tr = stdTable.getElementsByTagName(“tr”);
for (a = 0; a < tr.length; a++) {
td0 = tr[a].getElementsByTagName(“td”)[0];
td1 = tr[a].getElementsByTagName(“td”)[1];
if (td0 || td1) {
if (td0.innerHTML.toUpperCase().indexOf(filterTxt) > -1 || td1.innerHTML.toUpperCase().indexOf(filterTxt) > -1) {
tr[a].style.display = “”;
} else {
tr[a].style.display = “none”;
}
}
}
}
</script>
</body>
</html>



Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.