Filter html table with multiple search in two columns
Posted: 17 Mar 2019, 06:48
I'm trying to do this: w3schools.com/howto/howto_js_filter_table.asp
- But instead, to search with multiple search words in two columns of the same html table.
In the example above, I would want not only to filter by "name", but also by "Country".
This is the JavaScript code i tried.
- But instead, to search with multiple search words in two columns of the same html table.
In the example above, I would want not only to filter by "name", but also by "Country".
This is the JavaScript code i tried.
Code: Select all
function myFunction() {
// Declare variables
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
// Loop through all table rows, and hide those who don't match the search query
for (i = 0; i < tr.length; i++) {
td1 = tr[i].getElementsByTagName("td")[0];
if (td1) {
txtValue1 = td1.textContent || td1.innerText;
if (txtValue1.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
// this is what i've tried adding, but oviously, it conflicts with the first loop when matching
for (j = 0; j < tr.length; j++) {
td2 = tr[j].getElementsByTagName("td")[1];
if (td2) {
txtValue2 = td2.textContent || td2.innerText;
if (txtValue2.toUpperCase().indexOf(filter) > -1) {
tr[j].style.display = "";
} else {
tr[j].style.display = "none";
}
}
}
}