简体   繁体   中英

Filter/Search Table on Two Columns and Hide Rows

I can't figure out the following; I have a simple JS script that filters/hides rows of the table based on a search value. How can I search two columns td0 and td1 at the same time?

function myFunction() {
      // Declare variables 
      var input, filter, table, tr, td0,td1, i, txtValue;
      input = document.getElementById("myInput");
      filter = input.value.toUpperCase();
      table = document.getElementById("myTable");
      tr = table.getElementsByTagName("tr");

      
      for (i = 0; i < tr.length; i++) {
        td0 = tr[i].getElementsByTagName("td")[0];
        td1 = tr[i].getElementsByTagName("td")[1];

       // search first column
        if (td0) {
          txtValue = td0.textContent || td0.innerText;
          if (txtValue.toUpperCase().indexOf(filter) > -1) {
            tr[i].style.display = "";
          } else {
            tr[i].style.display = "none";
          }
        } 
       
       // search second column
       if (td1) {
              txtValue = td1.textContent || td1.innerText;
              if (txtValue.toUpperCase().indexOf(filter) > -1) {
                tr[i].style.display = "";
              } else {
                tr[i].style.display = "none";
              }
            } 
      }
    }

I'm sure that this is not the right approach though. I am trying to search both td0 and td1 at the same time. Any help would be greatly appreciate it!

Javascript can only run single thread. If you really want to run these two codes together at the same time, you need to use Web Workers to use threading, but I think this will be overkill for this task.

You can somehow run it together by using setTimeout , but in reality this will not run in parallel because it is single threaded. Note: this is a hacky way of doing this.

Example:

setTimeout(function() {
    //search td1
},0);

setTimeout(function() {
    //search td2
},0);

I suggest you use $.Deferred , much better.

Web workers: link Deferred: link

I just figure it out. A super simple JQuery:

$(document).ready(function(){
  $("#myInput").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    $("#myTable tr").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
  });
});

I don't even know how I missed this. Thanks for help anyways!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM