Trying to use an array of indexes for a custom live search via js

Advertisements

This is my code… I would basically like to make this line
(td = tr[i].querySelectorAll(".table-data")[0];)
I want this part…[0] to be something like this [0,5]

This is a sample code

function myFunction() {
  var input, filter, table, tr, td, i, txtValue;  
  input = document.querySelector("#myInput");
  filter = input.value.toUpperCase();
  table = document.querySelector("#myTable");
  tr = table.querySelectorAll(".row"); 
  for (i = 0; i < tr.length; i++) {
    td = tr[i].querySelectorAll(".table-data")[0];
    if (td) {
      txtValue = td.textContent || td.innerText;
      if (txtValue.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }       
  }
}

>Solution :

You need to iterate through each column as well and check if that value is found.

function myFunction() {
  var input, filter, table, tr, td, i, txtValue;
  input = document.querySelector("#myInput");
  filter = input.value.toUpperCase();
  table = document.querySelector("#myTable");
  tr = table.querySelectorAll(".row");
  for (i = 0; i < tr.length; i++) {
    td = tr[i].querySelectorAll(".table-data");
    if (td) {
      let valid = false;
      for (t = 0; t < td.length; t++) {
        txtValue = td[t].textContent || td[t].innerText;
        if (txtValue.toUpperCase().indexOf(filter) > -1) {
          valid = true;
        }
      }
      
      if (valid) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }       
  }
}

Leave a ReplyCancel reply