How to filter a html table using simple Javascript?

Creating a table filter using JavaScript or jQuery is a great way to enhance user experience when dealing with large datasets. Below is a simple example that demonstrates how to implement a table filter:

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Table Filter</title>
   </head>
   <body>
      <input type="text" id="searchInput" placeholder="Search...">
      <table id="dataTable">
         <thead>
            <tr>
               <th>Name</th>
               <th>Age</th>
               <th>City</th>
            </tr>
         </thead>
         <tbody>
            <tr>
               <td>John Doe</td>
               <td>30</td>
               <td>New York</td>
            </tr>
            <tr>
               <td>Jane Smith</td>
               <td>25</td>
               <td>Los Angeles</td>
            </tr>
            <!-- Add more rows as needed -->
         </tbody>
      </table>
      <script>
         document.getElementById('searchInput').addEventListener('keyup', function() {
             let input = this.value.toLowerCase();
             let rows = document.querySelectorAll('#dataTable tbody tr');
         
             rows.forEach(row => {
                 let cells = row.getElementsByTagName('td');
                 let match = Array.from(cells).some(cell => cell.textContent.toLowerCase().includes(input));
                 row.style.display = match ? '' : 'none';
             });
         });
      </script>
   </body>
</html>

administrator

Leave a Reply

Your email address will not be published. Required fields are marked *