ArticleZip > How To Filter A Html Table Using Simple Javascript

How To Filter A Html Table Using Simple Javascript

Filtering a HTML table using JavaScript can be a great way to enhance user experience on your website. By implementing a filter function, you can make it easier for users to search and find specific data within a large table. In this article, we will guide you through the process of filtering a HTML table using simple JavaScript.

To get started, you will first need to create a basic HTML table structure in your web page. You can use the following code snippet as a template:

Html

<table id="myTable">
  <thead>
    <tr>
      <th>Name</th>
      <th>Age</th>
      <th>Email</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>John Doe</td>
      <td>30</td>
      <td>[email protected]</td>
    </tr>
    <!-- Add more rows as needed -->
  </tbody>
</table>

Next, you will need to write a simple JavaScript function to enable filtering on this table. Here's an example function that filters the table based on user input:

Javascript

function filterTable() {
  var input, filter, table, tr, td, i, txtValue;
  input = document.getElementById('myInput');
  filter = input.value.toUpperCase();
  table = document.getElementById('myTable');
  tr = table.getElementsByTagName('tr');

  for (i = 0; i <tr> -1) {
        tr[i].style.display = '';
      } else {
        tr[i].style.display = 'none';
      }
    }
  }
}

In the above JavaScript function, we are obtaining user input from an input field with the id 'myInput'. We then iterate through each row of the table and compare the input value with the content of the specified column (in this case, the first column). If the text matches the filter, we display the row; otherwise, we hide it.

To make the filtering interactive, you can add an input field above the table where users can type their search query. You also need to call the `filterTable` function whenever the input value changes. Here's how you can do it:

Html

By adding this input field and onkeyup event listener, users can now easily filter the table based on the text they enter. This simple JavaScript solution provides a user-friendly way to search and filter data in a HTML table on your website.

In conclusion, filtering a HTML table using JavaScript doesn't have to be complicated. By following the steps outlined in this article, you can quickly implement a filtering functionality that enhances the usability of your web page. Experiment with different ways to customize the filtering logic to suit your specific needs and create a seamless user experience for your site visitors.

×