Javascript search and filter table

Viewed 323

I want to program a js function that allows me to search in a table. I want to show only those rows , that contain the search text in any of the

While I was able to make it work for a specific column only, I did not succeed for an entire row. So I guess it is somewhere in the inner for loop. Any idea where I am doing it wrong?

Thanks for your support! Here is my code:

function myFunction() {
var input, filter, table, tr, td, i, txtValue, allText, j;
input = document.getElementById("ipt-Search"); //my input text field where I enter the search term
filter = input.value.toUpperCase();
table = document.getElementById("tbl-RS"); // the table I want to search and filter
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
    allText = "";
    for (j = 0; j < tr.cells.length; j++) {
        td = tr[i].getElementsByTagName("td")[j];
        if (td) {
            allTest = all Test + " " + td.textContent || td.innerText;
        }
    }
    if (allText.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
    } else {
        tr[i].style.display = "none";
    }
}

}

2 Answers

Found an answer:

<script>
function myFunction() {
    var input, filter, table, tr, td, i, txtValue;
    input = document.getElementById("ipt-Search");
    filter = input.value.toUpperCase();
    table = document.getElementById("tbl-RS");
    tr = table.getElementsByTagName("tr");

    for (i = 1; i < tr.length; i++) {
    // Hide the row initially.
    tr[i].style.display = "none";

    td = tr[i].getElementsByTagName("td");
    for (var j = 0; j < td.length; j++) {
      cell = tr[i].getElementsByTagName("td")[j];
      if (cell) {
        if (cell.innerHTML.toUpperCase().indexOf(filter) > -1) {
          tr[i].style.display = "";
          break;
        }
      }
    }
}
}
</script>

I saw you found your answer. May I add a solution that is more up to date? This solution uses the ES6. It's nice to follow the advancement of javascript.

const myFunction = () => {
  let txtValue, filter;
  const input = document.getElementById("myInput");
  const table = document.getElementById("myTable");
  filter = input.value.toUpperCase();
  for (tr of table.getElementsByTagName("tr")) 
    for(td of tr.getElementsByTagName("td"))
        if (td) {
            txtValue = td.textContent || td.innerText;
            if (txtValue.toUpperCase().indexOf(filter) > -1){
                tr.style.display = "";
                break;
            }
            else 
                tr.style.display = "none"; 
        }   
    }
Related