Table Row Data Highlight On Click Using jQuery

This blog will show you, how you can highlight the table row at the click of the mouse on row of HTML table, using jQuery. In this blog, I will show you three ways by which, you can highlight the clicked row to HTML table.
 
First, we need to add the reference, given below-
  1. <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>  
Way 1. In this section, we will apply for each loop to highlight the clicked row. 
  1. $('#tableId tbody>tr').each(function () {  
  2.     if ($(this).hasClass('highlight')) {  
  3.         var nRowIndex = $(this).index();  
  4.         if (parseInt(nRowIndex,10) % 2 == 0)  
  5.             $(this).removeClass().addClass('Even');  
  6.         else  
  7.             $(this).removeClass().addClass('Odd');  
  8.         return;  
  9.     }  
  10. });  
  11. $(this).removeClass().addClass('highlight');  
Way 2.  In this section, we will apply using for loop to highlight the clicked row. 
  1. for (i = 0; i < $('#tableId tbody>tr').length; i++) {   
  2.         var tr=$('#tblDevelopers tbody>tr').eq(i);  
  3.         if (tr.hasClass('highlight')) {  
  4.         var nRowIndex = tr.index();  
  5.         if (parseInt(nRowIndex,10) % 2 == 0)  
  6.             tr.removeClass().addClass('Even');  
  7.         else  
  8.             tr.removeClass().addClass('Odd');  
  9.         break;  
  10.     }     
  11. }  
  12. $(this).removeClass().addClass('highlight');  
Way 3. In this section, we will use storing previous index/property.
  1. $('#tableIdtbody tr').click(function () {  
  2.         var nRowIndex = $('#<%= HiddenField1.ClientID %>').val();  
  3.         if (nRowIndex.length > 0)   
  4.         {  
  5.             if (parseInt(nRowIndex,10) % 2 == 0)  
  6.                 $('#tableId tbody tr').eq(nRowIndex).removeClass().addClass('Even');  
  7.             else  
  8.                 $('#tableId tbody tr').eq(nRowIndex).removeClass().addClass('Odd');  
  9.         }  
  10.    
  11.         $(this).removeClass().addClass('highlight');  
  12.         $('#<%= HiddenField1.ClientID %>').val($(this).index());  
  13.    
  14.     });  
Now, check the output. Just make HTML table and use the code, mentioned above. 
 
row
Ebook Download
View all
Learn
View all