Explain Codes LogoExplain Codes Logo

How to Perform a Real Time Search and Filter on a HTML Table

javascript
debouncing
performance-optimization
dom-manipulation
Anton ShumikhinbyAnton Shumikhin·Sep 16, 2024
TLDR

Create an easy-to-use search tool that filters out an HTML table using a combination of JavaScript's keyup event and simple DOM manipulation.

// Alternative name: The table "hide and seek" function function filterTable() { // Retrieve and clean up the search term let search = document.getElementById("searchInput").value.toUpperCase().trim(); let rows = document.getElementById("myTable").rows; // Loop through all table rows, hide those that don't match the search query for (let i = 0; i < rows.length; i++) { let firstCol = rows[i].cells[0].textContent.toUpperCase(); rows[i].style.display = firstCol.includes(search) ? "" : "none"; // No match? Hide and seek champion! Match? Found you! } } // Bind the search box with the filter function document.getElementById('searchInput').addEventListener('keyup', filterTable);

Add an input for search terms:

<input type="text" id="searchInput" placeholder="Just type and see magic..."> <table id="myTable"> <!-- Here be your table data --> </table>

This code supports real-time, responsive, and quick search results. As the user types, the table immediately updates.

Optimizing and Handling User Input

Advanced Performance Optimization

While the keyup event will keep your search up-to-date, without optimization, it could result in lag and excessive DOM manipulations. We tackle it by:

  • Introducing debouncing to wait a bit before executing the function, preventing too many operations and providing a smoother experience.
  • Using indexOf and transforming all text data to upper case (toUpperCase) makes the search case-insensitive—a seamless user experience, indeed.

Sanitizing User Inputs

Ensure to sanitize and trim the search string before performing the search to avoid getting hung on unintended search results or extra white spaces.

Using Regular Expressions for Flexibility

Introduce Regular Expressions for complex searches like wildcard matching or loose matching:

// We've upgraded the name: The "hide, seek, and wildcard" function function regexFilterTable() { // Input cleaning let search = document.getElementById("searchInput").value.trim(); let searchRegex = new RegExp(search, "i"); // Case-insensitive search let rows = document.getElementById("myTable").rows; // Loop through all table rows, and seek that champion hide and seeker for (let i = 0; i < rows.length; i++) { rows[i].style.display = searchRegex.test(rows[i].textContent) ? "" : "none"; // Wildcard champion or filtered out? } } // Remember .addEventListener? Let's bring in Mr. Debouncer for better performance! let timer; document.getElementById('searchInput').addEventListener('keyup', function() { clearTimeout(timer); timer = setTimeout(() => regexFilterTable(), 300); // Wait for 300ms after typing stops });

Reduce Overhead and Enhance Accessibility

By utilizing smart DOM handling, you can reduce overhead and increase execution speed:

  • Cache elements, such as your table or rows, to avoid repeated DOM queries.
  • Accessible functions enhance screen reader support, ensuring all users feel welcomed.

User-Friendly Features

Improve navigation by adding features like a counter stating the number of matches found and displaying only results after a minimum count of characters typed.

Fast and Maintainable Functions

Making a function reusable by tying it to different tables creates more flexible, maintainable code.

function applySearchToTable(tableId, inputId) { // … filter happy function here } // Use this guardian function for different tables and search boxes, saving lines of code