Filtering table multiple columns

前端 未结 14 1725
闹比i
闹比i 2020-12-09 13:31

I used w3School code for my page and it works fine but it only filters one column, don’t know how create loops but hopping there is easier solution.

    td =         


        
14条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-09 14:13

    function filterTable(event) {
        var filter = event.target.value.toUpperCase();
        var rows = document.querySelector("#myTable tbody").rows;
        
        for (var i = 0; i < rows.length; i++) {
            var firstCol = rows[i].cells[0].textContent.toUpperCase();
            var secondCol = rows[i].cells[1].textContent.toUpperCase();
            if (firstCol.indexOf(filter) > -1 || secondCol.indexOf(filter) > -1) {
                rows[i].style.display = "";
            } else {
                rows[i].style.display = "none";
            }      
        }
    }
    
    document.querySelector('#myInput').addEventListener('keyup', filterTable, false);
    
    
    Name Country
    Alfreds Futterkiste Germany
    Berglunds snabbkop Sweden
    Island Trading UK
    Koniglich Essen Germany
    Laughing Bacchus Winecellars Canada
    Magazzini Alimentari Riuniti Italy
    North/South UK
    Paris specialites France

提交回复
热议问题