How to add a filter to a table with javascript

22 Nov 2022

➤ only one column

➤ only one column

Working with:

HTML

<input id="myInput" type="text" />

<table id="myTable">

JS

Adding multiple columns to be included in filter by defining a var for each column and using ||:

<script>

    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);

    </script>

links

social