Live search is a powerful feature that allows users to filter the information in real-time while they are typing. In this blog post, we will learn how to create a live search on an HTML table using jQuery, a popular JavaScript library. Let’s start!
Create the HTML Table
First, let’s create a simple HTML table:
<table id="myTable"> <thead> <tr> <th>Name</th> <th>Country</th> </tr> </thead> <tbody> <tr> <td>John</td> <td>USA</td> </tr> <tr> <td>Michael</td> <td>Canada</td> </tr> ... </tbody> </table>
Add a Search Input Field
Now, let’s add an input field above the table, which we will use to type the search query:
<input type="text" id="myInput" placeholder="Search for names..">
Include jQuery Library
Before writing any jQuery code, make sure to include the jQuery library in your document:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
Implement Live Search with jQuery
Now, let’s write the jQuery code for the live search functionality. We will listen for the keyup event on the input field, and then filter the table rows based on the input value:
$(document).ready(function(){ $("#myInput").on("keyup", function() { var value = $(this).val().toLowerCase(); $("#myTable tbody tr").filter(function() { $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1) }); }); });Let’s break down the code above:
- $(document).ready(function(){…}); ensures that the code inside will only run once the entire page’s DOM is ready.
- $(“#myInput”).on(“keyup”, function() {…}); adds an event listener for the keyup event on the input field with the ID “myInput”.
- var value = $(this).val().toLowerCase(); gets the input field’s value and converts it to lowercase.
- $(“#myTable tbody tr”).filter(function() {…}); selects all table rows within the “myTable” table’s tbody and applies a filter function to them.
- $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1); checks if the input value exists in the table row’s text content. If it does, the table row is shown; otherwise, it is hidden.
Done!
That’s it! You have successfully implemented a live search feature on an HTML table using jQuery. Now your users can easily search and filter the information they need.