Filtering table multiple columns

前端 未结 14 1726
闹比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条回答
  •  南笙
    南笙 (楼主)
    2020-12-09 14:33

    Enhanced Rob.M's answer to suit multi-column search with below code.

    function filterTable(event) {
    //Convert search value to uppercase and assign the value to variable 'filter'
    var filter = event.target.value.toUpperCase();
    //Find total rows in the table's body
    var rows = document.querySelector("#table tbody").rows;
    //Start looping rows
    for (var i = 0; i < rows.length; i++) {
        //Count the columns in current row
        var colCount = $("#table th").length;
        //Assign a variable 'res' for result counting
        var res = 1;
        //Start looping columns in current row
        for (let j = 0; j < colCount; j++) {
            //Iterate single cell and convert the contents to uppercase, assign the content to variable 'x'
            var x = "col_" + j;
            var x = rows[i].cells[j].textContent.toUpperCase();
            //find the position of first index of the search value.
            //If search value found ADD 1 to 'res' else LESS 1
            x.indexOf(filter) > -1 ? res++ : res--;
        }
        //Convert the colCount variable to absolute value
        colCount = -Math.abs(colCount - 1);
        //Display or hide the row, based on result condition
        res > colCount || filter == "" ? (rows[i].style.display = "") : (rows[i].style.display = "none");
    }
    

    }

提交回复
热议问题