Filtering table multiple columns

前端 未结 14 1731
闹比i
闹比i 2020-12-09 13:31

I used w3School code for my page and it works fine but it only filters one column, don’t know how create loops but hopping there is easier solution.

    td =         


        
14条回答
  •  没有蜡笔的小新
    2020-12-09 14:13

    Your code is fine. To add multiple columns you need to add || condition (in if clause).

    The problem with Rob's answer is it will filter out table headings if you use tr.

    Here is extension to code:

    function myFunction() {
    var input, filter, table, tr, td, i;
      input = document.getElementById("myInput");
      filter = input.value.toUpperCase();
      table = document.getElementById("myTable");
      tr = table.getElementsByTagName("tr");
      for (i = 0; i < tr.length; i++) {
        td = tr[i].getElementsByTagName("td")[0]; // for column one
         td1 = tr[i].getElementsByTagName("td")[1]; // for column two
    /* ADD columns here that you want you to filter to be used on */
        if (td) {
          if ( (td.innerHTML.toUpperCase().indexOf(filter) > -1) || (td1.innerHTML.toUpperCase().indexOf(filter) > -1) )  {            
            tr[i].style.display = "";
          } else {
            tr[i].style.display = "none";
          }
        }
      }
    } 
    

提交回复
热议问题