From 08298420d67f8844c7111e3447ba2dd281f6c38c Mon Sep 17 00:00:00 2001 From: Andrew Gioia Date: Tue, 26 Sep 2023 19:15:10 +0000 Subject: [PATCH] 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. --- JavaScript/live_table_filtering.js | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 JavaScript/live_table_filtering.js diff --git a/JavaScript/live_table_filtering.js b/JavaScript/live_table_filtering.js new file mode 100644 index 0000000..08093d5 --- /dev/null +++ b/JavaScript/live_table_filtering.js @@ -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'); + } + } +}); \ No newline at end of file