Adds live table filtering javascript snippet

This event handler updates a table's rows based on a search input value. Each change to the input will trigger a refresh of the table rows, and zebra striping is redone based on the new result set.
This commit is contained in:
Andrew Gioia 2023-09-26 19:15:10 +00:00
parent 2f74596859
commit 08298420d6

View File

@ -0,0 +1,26 @@
document.getElementById('searchInput').addEventListener('input', function(event) {
// get the query and table rows
let q = this.value;
let rows = document.querySelectorAll('tr.result-row');
let results = 0;
let odd = 1;
// toggle the classnames to show/hide and redo zebra stripes
for (var i = 0; i < rows.length; i++) {
// toggle classes
if (rows[i].innerText.toLowerCase().includes(q.toLowerCase())) {
rows[i].className = (odd) ? 'result-row bg-gray-100 dark:bg-gray-800' : 'result-row';
results = results + 1;
odd = (odd) ? 0 : 1;
} else {
rows[i].className = 'result-row hidden';
}
// if there are no results, show the empty message
if (results == 0) {
document.getElementById('noResults').classList.remove('hidden');
} else {
document.getElementById('noResults').classList.add('hidden');
}
}
});