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:

My Customers

Name Country
Alfreds Futterkiste Germany
Berglunds snabbkop Sweden
Island Trading UK
Koniglich Essen Germany
Laughing Bacchus Winecellars Canada
Magazzini Alimentari Riuniti Italy
North/South UK
Paris specialites France

Similar Topics