【问题标题】:How to search 2nd column of table instead of 1st column如何搜索表格的第二列而不是第一列
【发布时间】:2021-12-16 21:17:31
【问题描述】:

我在我的 Bootstrap 表中添加了一个搜索框。所以添加的第一件事是这个输入,它工作正常,但我需要搜索 Country 名称而不是 Names

function myFunction() {
  // Declare variables
  var input, filter, table, tr, td, i, txtValue;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  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) {
      txtValue = td.textContent || td.innerText;
      if (txtValue.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
}
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names..">


<table id="myTable">
  <tr class="header">
    <th style="width:60%;">Name</th>
    <th style="width:40%;">Country</th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Germany</td>
  </tr>
</table>

【问题讨论】:

    标签: javascript html twitter-bootstrap html-table twitter-bootstrap-3


    【解决方案1】:
    1. td = tr[i].getElementsByTagName("td")[1];
    2. 我建议你只搜索 tbody
    3. 也使用事件监听器

    document.getElementById("myInput").addEventListener("keyup",function() {
      // Declare variables
      const filter = this.value.toUpperCase();
      const trs = document.querySelectorAll("#myTable tbody tr");
      // Loop through all table rows, and hide those who don't match the search query
      trs.forEach(tr => {
        const td = tr.cells[1];
        txtValue = td.textContent.toUpperCase()
        tr.hidden = txtValue && !txtValue.includes(filter)
      })
    });
    <input type="text" id="myInput" placeholder="Search for names.." autocomplete="off">
    <table id="myTable">
      <thead>
        <tr class="header">
          <th style="width:60%;">Name</th>
          <th style="width:40%;">Country</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>Alfreds Futterkiste</td>
          <td>Germany</td>
        </tr>
        <tr>
          <td>Microsoft</td>
          <td>USA</td>
        </tr>
      </tbody>
    </table>

    【讨论】:

    • 好像不行!
    • @nagidi 怎么样。它至少在这里工作。你添加了 THEAD 和 TBODY 吗?
    猜你喜欢
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-10
    • 1970-01-01
    相关资源
    最近更新 更多