简体   繁体   English

Javascript 搜索和过滤表

[英]Javascript search and filter table

I want to program a js function that allows me to search in a table.我想编写一个 js function 允许我在表中搜索。 I want to show only those rows, that contain the search text in any of the我只想显示那些包含搜索文本的行

While I was able to make it work for a specific column only, I did not succeed for an entire row.虽然我能够使其仅适用于特定列,但我并没有成功完成整行。 So I guess it is somewhere in the inner for loop.所以我猜它在内部 for 循环中的某个地方。 Any idea where I am doing it wrong?知道我在哪里做错了吗?

Thanks for your support: Here is my code:感谢您的支持:这是我的代码:

function myFunction() {
var input, filter, table, tr, td, i, txtValue, allText, j;
input = document.getElementById("ipt-Search"); //my input text field where I enter the search term
filter = input.value.toUpperCase();
table = document.getElementById("tbl-RS"); // the table I want to search and filter
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
    allText = "";
    for (j = 0; j < tr.cells.length; j++) {
        td = tr[i].getElementsByTagName("td")[j];
        if (td) {
            allTest = all Test + " " + td.textContent || td.innerText;
        }
    }
    if (allText.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
    } else {
        tr[i].style.display = "none";
    }
}

} }

Found an answer:找到了答案:

<script>
function myFunction() {
    var input, filter, table, tr, td, i, txtValue;
    input = document.getElementById("ipt-Search");
    filter = input.value.toUpperCase();
    table = document.getElementById("tbl-RS");
    tr = table.getElementsByTagName("tr");

    for (i = 1; i < tr.length; i++) {
    // Hide the row initially.
    tr[i].style.display = "none";

    td = tr[i].getElementsByTagName("td");
    for (var j = 0; j < td.length; j++) {
      cell = tr[i].getElementsByTagName("td")[j];
      if (cell) {
        if (cell.innerHTML.toUpperCase().indexOf(filter) > -1) {
          tr[i].style.display = "";
          break;
        }
      }
    }
}
}
</script>

I saw you found your answer.我看到你找到了答案。 May I add a solution that is more up to date?我可以添加一个更新的解决方案吗? This solution uses the ES6.此解决方案使用 ES6。 It's nice to follow the advancement of javascript.很高兴跟随 javascript 的进步。

const myFunction = () => {
  let txtValue, filter;
  const input = document.getElementById("myInput");
  const table = document.getElementById("myTable");
  filter = input.value.toUpperCase();
  for (tr of table.getElementsByTagName("tr")) 
    for(td of tr.getElementsByTagName("td"))
        if (td) {
            txtValue = td.textContent || td.innerText;
            if (txtValue.toUpperCase().indexOf(filter) > -1){
                tr.style.display = "";
                break;
            }
            else 
                tr.style.display = "none"; 
        }   
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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