Filtering table multiple columns

前端 未结 14 1678
闹比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:36

    I just used the same W3 code that you started with, and I found this fairly elegant solution -- which should work for large numbers of columns

        function myFunction() {
      var input, filter, table, tr, td, i, txtValue;
      input = document.getElementById("myInput");
      filter = input.value.toUpperCase();
      table = document.getElementById("mainTable");
      tr = table.getElementsByTagName("tr");
      for (i = 0; i < tr.length; i++) {
        td = tr[i].getElementsByTagName("td")[0];
        td2 = tr[i].getElementsByTagName("td")[1];
        if (td || td2) {
          txtValue = td.textContent || td.innerText;
          txtValue2 = td2.textContent || td2.innerText;
          if (txtValue.toUpperCase().indexOf(filter) > -1 || txtValue2.toUpperCase().indexOf(filter) > -1 ) {
            tr[i].style.display = "";
          } else {
            tr[i].style.display = "none";
          }
        }       
      }
    }
    
    0 讨论(0)
  • 2020-12-09 14:36

    I uploaded the code here to search table data among two columns

    function searching() {
        var input, filter, table, tr, td1, td2, i, txtValue;
        input = document.getElementById("search");
        filter = input.value.toUpperCase();
        table = document.getElementById("table");
        tr = table.getElementsByTagName("tr");
    
        for (i = 0; i < tr.length; i++) { 
            td1 = tr[i].getElementsByTagName("td")[0];
            td2 = tr[i].getElementsByTagName("td")[1];
            if (td1 || td2) {
                txtValue1 = td1.textContent || td1.innerText;
                txtValue2 = td2.textContent || td2.innerText;
                if (txtValue1.toUpperCase().indexOf(filter) > -1 || (txtValue2.toUpperCase().indexOf(filter) > -1)) {
                    tr[i].style.display = "";
                } else {
                    tr[i].style.display = "none";
                }
            }
        }
    }
    
    
    <input class="form-control my-3" id="search" onkeyup="searching()" type="search" placeholder="Search To-Do items here..." aria-label="Search">
    
    
    <table class="table my-5">
        <thead class="thead-dark">
            <tr>
                <th scope="col ">Sr No.</th>
                <th scope="col ">Item</th>
                <th scope="col ">Description</th>
                <th scope="col ">Manage</th>
            </tr>
        </thead>
        <tbody id="table">
        </tbody>
    </table>

    0 讨论(0)
提交回复
热议问题