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

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

问题描述:

现在搜索仅从第一列开始搜索。我已经采取了代码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"; 
     } 
    } 
    } 
} 

试试这个

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"; 
     } 
    } 
    } 
} 

工作fiddle

+0

EBi编程的答案更通用。 –

+0

这个解决方案工作正常,但问题是我的第一个td是超链接到模式。所以搜索也在锚标签内搜索。我只想搜索id或锚标签外的内容。请看看@VaibhavBansal这里是我的第一个td的代码'​​718'。 –

+0

@LoveneetSaini更新小提琴https://jsfiddle.net/vaibhavb93/rk49opdm/ 它只会搜索td文本和锚点ID。不锚文本 –

您需要延长您的循环,包括多列,以及:

//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) {} 

     } 

    } 

}