December 22, 2016 · javascript
html table search with pure javascript
The below javascript method searches through all the <td>
elements and hides <tr>
that do not have it.
function search() {
// Declare variables
var input, filter, table, tr, td, i, j, tds, ths, matched;
input = document.getElementById("searchInput");
filter = input.value.toUpperCase();
tr = document.getElementsByTagName("tr");
// Loop through all table rows, and hide
// those who don't match the search query
for (i = 0; i < tr.length; i++) {
tds = tr[i].getElementsByTagName("td");
ths = tr[i].getElementsByTagName("th");
matched = false;
// leave the row header
if (ths.length > 0) {
matched = true;
}
else {
for (j = 0; j < tds.length; j++) {
td = tds[j];
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
matched = true;
break;
}
}
}
if (matched == true) {
tr[i].style.display = "";
}
else {
tr[i].style.display = "none";
}
}
}
And the below adds the search input box to the webpage and maps it to our search
method
<input type="text" id="searchInput" onkeyup="search()" placeholder="Search..">