How to filter a very large bootstrap table using pure Javascript

前端 未结 7 2155
清歌不尽
清歌不尽 2021-02-05 12:05

I\'ve built a large table in bootstrap, about 5,000 rows x 10 columns, and I need to filter the table for specific attributes, fast, using only JavaScript. The table has both an

7条回答
  •  不知归路
    2021-02-05 12:59

    Here is a on the fly filter solution, that filter the table using letters typed in input box on keypress event.

    Though right now I am using DataTables in my current project development, yet if you want a strict javascript solution here is it. It may not be the best optimized but works good.

    function SearchRecordsInTable(searchBoxId, tableId) {
        var searchText = document.getElementById(searchBoxId).value;
        searchText = searchText.toLowerCase();
        var targetTable = document.getElementById(tableId);
        var targetTableColCount;
    
        //Loop through table rows
        for (var rowIndex = 0; rowIndex < targetTable.rows.length; rowIndex++) {
            var rowData = '';
    
            //Get column count from header row
            if (rowIndex == 0) {
                targetTableColCount = targetTable.rows.item(rowIndex).cells.length;
                continue; //do not execute further code for header row.
            }
    
            //Process data rows. (rowIndex >= 1)
            for (var colIndex = 0; colIndex < targetTableColCount; colIndex++) {
                rowData += targetTable.rows.item(rowIndex).cells.item(colIndex).textContent;
                rowData = rowData.toLowerCase();
            }
            console.log(rowData);
    
            //If search term is not found in row data
            //then hide the row, else show
            if (rowData.indexOf(searchText) == -1)
    
    
                targetTable.rows.item(rowIndex).style.display = 'none';
            else
                targetTable.rows.item(rowIndex).style.display = '';
        }
    }
    

    Cheers!!

提交回复
热议问题