December 15 2013

Jquery highlight table row on click

Tagged Under :

jquery
To highlighter table row when user click the row. The easy way was add a css class on table “tr”.

How to add a css on “tr”? you need used JQuery to perform this action.

Before that, you need a table like below:
<div id="gridview">
  <table border="1" cellpadding="0" cellspacing="0" width="100%">
    <tr>
      <td>Row 1</td>        
    </tr>
    <tr>
      <td>Row 2</td>        
    </tr>
    <tr>
      <td>Row 3</td>            
    </tr>
    <tr>
      <td>Row 4</td>        
    </tr>
  </table>
</div>

And then add the “highlighted” css class as well
.highlighted {
    color: #261F1D
    background-color: #E5C37E;
}

After that, you can add the JQuery script in your page.
$('table').on('click', 'tr', function () {
    var selected = $(this).hasClass('highlighted');
    $('.highlighted').removeClass('highlighted');
    if (!selected) { $(this).addClass('highlighted'); }
});

Above script only can highlighted 1 row only. But if you want highlight multiple row, you can use script as below:
$("#gridview tr").click(function() {
    $(this).toggleClass("highlighted");
}); 

Make a Comment

You must be logged in to post a comment.