简体   繁体   English

如何创建过滤器搜索以从表的两列中搜索数据?

[英]How to create a filter search to search data from two columns in a table?

Right now the search is searching from only first column. 现在,搜索仅从第一列开始。 I have taken the code from w3schools Here is the code: 我已经从w3schools获取了代码,这是代码:

function myFunction() {
// Declare variables
  var input, filter, table, tr, td, i;
  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) {
      if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
}

Try this 尝试这个

myFunction() {
  // Declare variables 
  var input, filter, table, tr, td, i;
  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++) {
    //Column 1
    td_1 = tr[i].getElementsByTagName("td")[0];
    //Column 2
    td_2 = tr[i].getElementsByTagName("td")[1];
    if (td_1 || td_2) {
      if (td_1.innerHTML.toUpperCase().indexOf(filter) > -1 || td_2.innerHTML.toUpperCase().indexOf(filter)> -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    } 
  }
}

Working fiddle 工作提琴

You will need to extend your loop to include multiple columns as well: 您将需要扩展循环以包括多个列:

//Get the column count
var columnCount = table.getElementsByTagName("tr")[0].childNodes.length;

for (i = 0; i < tr.length; i++) {

    for (j = 0; j < columnCount; j++) {

        td = tr[i].getElementsByTagName("td")[j];

        if (td) {

                var tempText;

                if(td.childNodes[1].getAttribute('id')){

                    tempText = td.childNodes[1].getAttribute('id');

                }                   
                else {

                    tempText = td.innerHTML.toUpperCase();

                }

                try {
                    if (tempText.indexOf(filter) > -1) {
                        tr[i].style.display = "";
                    } else {
                        tr[i].style.display = "none";
                    }
                }
                catch(err) {}

        }

    }

}

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

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