2017-01-23 2 views
0

今、検索は最初の列からのみ検索しています。私はここでw3schoolsからコードをとっているコードです:フィルタ検索を作成してテーブル内の2つの列からデータを検索するにはどうすればよいですか?

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

答えて

1

この

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 updated fiddle https://jsfiddle.net/vaibhavb93/rk49opdm/ これは、tdテキストとアンカーIDのみを検索します。アンカーテキストなし –

0

作業してみてください。

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

     } 

    } 

} 
関連する問題