Filter html table with multiple search in two columns
Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
-
Marius
- Posts: 107
Filter html table with multiple search in two columns
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.
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";
}
}
}
}
Admin
Posts: 805
Split the search string by space and filter the column for each word. Try this code in your JS script:
Code: Select all
function myFunction() {
var src, input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase().trim().split(' ');
table = document.getElementById("myTable");
for (j = 0; j < filter.length; j++) {
tr = table.getElementsByTagName("tr");
src = filter[j].trim();
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
td2 = tr[i].getElementsByTagName("td")[1];
if (src!='' && td && td2) {
txtValue = td.textContent || td.innerText;
txtValue2 = td2.textContent || td2.innerText;
if (txtValue.toUpperCase().indexOf(src) > -1 || txtValue2.toUpperCase().indexOf(src) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
}
- Demo:
Similar Topics
-
Multiple select for upload not working on mobile
JavaScript - jQuery - Ajax
First post
Plessant Coursesweb,
meight useless to ask but it seems this upload for picture-album is not working on my mobile-page
but on my computer I just...
Last post
Try to search on the internet for:
html multiple select upload mobile