2017-02-23 4 views
0

まずJavaScriptのエキスパートではないので、答えは簡単かもしれませんが、現在はこの(https://www.w3schools.com/howto/howto_js_filter_table.asp)チュートリアルを使用してテーブルをフィルタリングしていますが、 1つの列だけを検索することができます(この例では名前または国のみ)。しかし、同時に両方の列を検索する必要があります。JavaScriptを使用してテーブルをフィルタリング/検索する

このコードで変更する必要があるのは何ですか?

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

答えて

0
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]; // This code only get the frist "TD" element 
     tds = tr[i].getElementsByTagName("td"); 
     for (j = 0; j < td.length; j++) { 
      td = tds[j]; 
      if (td) { 
       if (td.innerHTML.toUpperCase().indexOf(filter) > -1) { 
        tr[i].style.display = ""; 
       } else { 
        tr[i].style.display = "none"; 
       } 
      } 
     } 

    } 
} 

}

0

あなたはアレイ(check this answer for ways to do it)にgetElementsByTagNameによって返さHTMLCollectionを変換してからtd値の '一部' は、あなたのfilterを一致させるかどうかを確認するためにsomeメソッドを使用することができます。一致するものがあれば、それを表示します。それ以外は隠す。ここでは、コードです:

function myFunction() { 
    const input = document.getElementById('myInput') 
    const filter = input.value.toLowerCase() 
    const table = document.getElementById('myTable') 
    const tr = [...table.getElementsByTagName('tr')] 

    tr.forEach((t) => { 
    const foundMatch = [...t.getElementsByTagName('td')].some((td) => { 
     return td.innerHTML.toLowerCase().indexOf(filter) > -1 
    }) 
    if (foundMatch) { 
     t.style.display = '' 
    } else { 
     t.style.display = 'none' 
    } 
    }) 
} 

はjsfiddle上のアクションでそれを確認してください:https://jsfiddle.net/marcusmonteiro/hsdyajbn/2/show/

関連する問題