0

First of all, I'm not an expert in JavaScript, so the answer will probably be simple, but currently I'm using this (https://www.w3schools.com/howto/howto_js_filter_table.asp) tutorial to filter through a table, but you can only search in 1 column, so in this example only for Name or Country, but I want to search in both columns at the same time.

What do I need to change in this code?

function myFunction() {
  // Declare variables 
  var input, filter, table, tr, td, i;
  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++) {
    td = tr[i].getElementsByTagName("td")[0];
    if (td) {
      if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
      tr[i].style.display = "none";
      }
    } 
  }
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Mark
  • 31
  • 1
  • 6

2 Answers2

0
function myFunction() {
    // Declare variables 
    var input, filter, table, tr, td, i;
    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++) {
        //td = tr[i].getElementsByTagName("td")[0]; // This code only get the frist "TD" element
        tds = tr[i].getElementsByTagName("td");
        for (j = 0; j < td.length; j++) {
            td = tds[j];
            if (td) {
                if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
                    tr[i].style.display = "";
                } else {
                    tr[i].style.display = "none";
                }
            }
        }

    }
}

}

zpc
  • 107
  • 4
0

You can convert the HTMLCollection returned by getElementsByTagName to an Array (check this answer for ways to do it) and then use the some method to check if 'some' of the tdvalues match your filter. If there is a match, display them. Else hide them. Here's the code:

function myFunction() {
  const input = document.getElementById('myInput')
  const filter = input.value.toLowerCase()
  const table = document.getElementById('myTable')
  const tr = [...table.getElementsByTagName('tr')]

  tr.forEach((t) => {
    const foundMatch = [...t.getElementsByTagName('td')].some((td) => {
      return td.innerHTML.toLowerCase().indexOf(filter) > -1
    })
    if (foundMatch) {
      t.style.display = ''
    } else {
      t.style.display = 'none'
    }
  })
}

Check it in action on jsfiddle: https://jsfiddle.net/marcusmonteiro/hsdyajbn/2/show/

Community
  • 1
  • 1