I have the below code which does a good job in searching for matches in one specific table column, but it would be nice if I could get it to search all columns in the HTML table. I just don’t know how I can modify the existing code to accomplish it. Any help would be appreciated!
I have isolated what part of this code deals with column selection – td = tr[i].getElementsByTagName("td")[0];
– but I don’t know how to modify it to loop through all values in that array as it searches for a match.
HTML
<input type="text" id="searchInput" onkeyup="tableSearch()" placeholder="Search for something ...">
JS
function tableSearch() {
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("searchInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
2
Answers
You could add a second for-loop inside the first one that loops over each td element and checks each value. Right now you’re only grabbing the first one of each row (
tr[i].getElementsByTagName("td")[0];
note the[0]
at the end).Something like this should do it:
You can use
some()
to check if anytd
in sametr
is match the input text.