DEV Community

Discussion on: Search and filter a table with JavaScript

Collapse
 
darkflux profile image
darkflux • Edited

seems like awful advanced coding for something so simple. i did it in about 18 lines of code.

it will even search multiple keywords, instead of just specific phrases. in fact, if you don't need/want that, you can remove 3 more lines of array code, and just use indexOf(val).

doesn't work for multiple tables, but you could easily modify it to.

document.getElementById('res-filter').addEventListener('keyup', filterList);
function filterList() {
    var srch = document.getElementById('res-filter');
    var val = srch.value.toLowerCase();
    var valArr = val.split(' ');
    var tbl = document.getElementById('res-table');
    var tblLength = tbl.rows.length;
    if (tblLength != 0) {
        for (var i = 1; i < tblLength; i++) {
            tbl.rows[i].style.display = 'table-row';
            for (var j = 0; j < valArr.length; j++) {
                if (tbl.rows[i].textContent.toLowerCase().indexOf(valArr[j]) === -1) {
                    tbl.rows[i].style.display = 'none';
                }
            }
        }
    }
}
Collapse
 
michelc profile image
Michel

I probably got a bit carried away, especially on optimization :)

Anyway, your code is great and the fact that you can search multiple keywords is interesting.