Live Search in HTML Table Using jQuery

Jquery is a javascript library and easy to learn. In this tutorial, we are going to make Live Search in HTML Table Using jQuery.

It may be a good idea to use jQuery for small data search instead of auto search OR data table. You have to use jQuery Selectors for making a live search in HTML table. (Know more about jQuery Selectors)

You have to write only 10-12 line code to make a live search in Html Table using jQuery for your small app. Here, I write sample code with an example. You can use it for your application.

Live Search In HTML Table Using jQuery
Live Search In HTML Table Using jQuery

 

First, you need to create simple HTML table with a class name.


<html>
   <head>
     <title>Live Search in HTML Table Using jQuery</title>
   </head>
   <body>
     <div class="form-group">
       <input type="text" class="form-control pull-right" style="width:20%" id="search" placeholder="Type to search table...">
     </div>
     <table class="table-bordered table pull-right" id="mytable" cellspacing="0" style="width: 100%;">
     <thead>
       <tr role="row">
         <th>Name</th>
         <th>Position</th>
         <th>Age</th>
         <th>Salary</th>
       </tr>
     </thead>
     <tbody>
       <tr>
         <td>Brad Gree</td>
         <td>Software Engineer</td>
         <td>41</td>
         <td>$132,000</td>
       </tr>
       <tr>
         <td>Wagner Kumar</td>
         <td>Software Engineer</td>
         <td>28</td>
         <td>$206,850</td>
       </tr>
       <tr>
         <td>Salman Khan</td>
         <td>Software Engineer</td>
         <td>38</td>
         <td>$163,500</td>
       </tr>
       <tr>
         <td>Zohair Raza</td>
         <td>Engineer</td>
         <td>30</td>
         <td>$433,060</td>
       </tr>
     </tbody>
   </table>
 </body>
</html>

Above code is simple HTML.

Now, include jQuery.


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

After including above jQuery. We have to add jQuery code snippet for Live search in HTML table.


<script>
   // Write on keyup event of keyword input element
   $(document).ready(function(){
     $("#search").keyup(function(){
     _this = this;
   
     // Show only matching TR, hide rest of them
     $.each($("#mytable tbody tr"), function() {
       if($(this).text().toLowerCase().indexOf($(_this).val().toLowerCase()) === -1)
       {  
           $(this).hide();
       }
       else
       {
          $(this).show();
       }
     });
  });
});
</script>

Above code work on on keyUp event to search records from HTML table. It’s really amazing use of jQuery for small application.

Let me know, If you have any queries OR suggestions.

 

Leave a Reply

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