'Filter table by values in all columns
I have created search input that filters table values in first column. How can I filter table values in all columns (except flag column)?
Search function code
function searchCountries() {
let search = document.getElementById("search").value.toUpperCase();
let tableRecord = document.getElementById("table");
console.log(search);
let tr = tableRecord.getElementsByTagName("tr");
for (let i = 0; i < tr.length; i++) {
let td = tr[i].getElementsByTagName("td")[0];
console.log(td);
if (td) {
let textvalue = td.textContent || td.innerText;
if (textvalue.toUpperCase().indexOf(search) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
html structure
<tr>
<td>${country.name}</td>
<td>${country.currencies[0].name}</td>
<td>${country.languages[0].name}</td>
<td>${country.population}</td>
<td>${country.area}</td>
<td><img src='${country.flag}'></img></td>
</tr>
Solution 1:[1]
You can use a loop to check all columns:
function searchCountries() {
let search = document.getElementById("search").value.toUpperCase();
let tableRecord = document.getElementById("table");
console.log(search);
let tr = tableRecord.getElementsByTagName("tr");
for (let i = 0; i < tr.length; i++) {
let displayStyle = "none";
let td = tr[i].getElementsByTagName("td");
for (let j = 0; j < td.length - 1; ++j) {
console.log(td[j]);
if (td[j]) {
let textvalue = td[j].textContent || td[j].innerText;
if (textvalue.toUpperCase().indexOf(search) > -1) {
displayStyle = "";
break;
}
}
}
tr[i].style.display = displayStyle;
}
}
img {
width: 20px;
}
<input id="search">
<button onclick="searchCountries()">Search</button>
<table id="table">
<tr>
<td>Name</td>
<td>Currency</td>
<td>Language</td>
<td>Population</td>
<td>Area</td>
<td><img src=https://cdn.pixabay.com/photo/2016/02/04/13/12/flag-1179172_960_720.png></td>
</tr>
<tr>
<td>Name 123</td>
<td>Currency1</td>
<td>Language</td>
<td>Population</td>
<td>Area</td>
<td><img src=https://cdn.pixabay.com/photo/2016/02/04/13/12/flag-1179172_960_720.png></td>
</tr>
</table>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
