搜索表的多个列

时间:2018-07-11 18:12:51

标签: javascript css html-table

我目前有一个可以过滤和搜索每个表的一列的表,但是我不确定如何编辑函数,以便将搜索应用于表的所有列。 这是我的功能,也是我的一张桌子:

  function myFunction(){
  var td, i;
  var input = document.getElementById("myInput");
  var filter = input.value.toUpperCase();
  var table = document.getElementById("myTable");
  var tr = table.getElementsByTagName("tr");

  // Loop through all table rows, and hide those who don't match the search query
  for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[0];
    if (td) {
      if (td.innerHTML.toUpperCase().indexOf(filter) > -1 ) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
}

<table className="table table-bordered" id="table2a">
          <tbody>
          <tr><th> Consumer System: </th>
          <td>System1 </td>
          <td>System2 </td>
          </tr>

          <tr>
          <th>Consumer Dev App Name: </th>
          <td> To be on-boarded </td>
          <td> To be on-boarded </td>
          </tr>

          <tr>
          <th> Contact Email Distribution </th>
          <td>TBD </td>
          <td> TBD </td>
          </tr>
          </tbody>
          </table>

1 个答案:

答案 0 :(得分:1)

对于表中的每一行,您将需要一个内部循环来迭代当前td中的每个tr

function myFunction(){
  var td, i, tdArr, j;
  var input = document.getElementById("myInput");
  var filter = input.value.toUpperCase();
  var table = document.getElementById("myTable");
  var tr = table.getElementsByTagName("tr");

  // Loop through all table rows
  for (i = 0; i < tr.length; i++) {
    tdArr = tr[i].getElementsByTagName("td");
    // Loop through all table columns in the current row, and hide those who don't match the search query
    for (j = 0; j < tdArr.length; j++) {
      td = tdArr[j];
      if (td) {
        if (td.innerHTML.toUpperCase().indexOf(filter) > -1 ) {
          tr[i].style.display = "";
        } else {
          tr[i].style.display = "none";
        }
      }
    }        
  }
}