jQuery to highlight GridView Rows when Checkbox is checked in ASP.NET

In this post, Find out jQuery code to highlight ASP.NET Gridview row when checkbox is checked and restore it to original state when unchecked.

Also Read:

How to do it?

  • Bind the click event to all the checkbox of ASP.NET GridView.
    $('#<%=gdRows.ClientID%>')
         .find('input:checkbox[id$="chkDelete"]')
         .click( function() {
    });
    
  • In the click event, first check whether the checkbox is checked or unchecked. And store the status in a variable.
    var isChecked = $(this).prop("checked");
  • After that find the respective row where checkbox is present. As we need to highlight that particular row only.
    var $selectedRow = $(this).parent("td").parent("tr");
  • If you have different color for alternate rows (see above image) then next few lines of code is required, otherwise you can skip it. For example, if all the rows of same color then skip this code. But if there are alternate color of GridView rows then it is required.As once we highlight the row, we can't find what was the previous color once it is unchecked. So the idea is to find the row index. Based on index value (even or odd) set color value in variable.
    var selectedIndex = $selectedRow[0].rowIndex;
    var sColor = '';
    if(selectedIndex%2 == 0)
        sColor = 'PaleGoldenrod';
    else
        sColor = 'LightGoldenrodYellow';
    
  • Now based on checkbox status, highlight the row (if checked). Otherwise restore it to previous color which is stored in sColor variable.
    if(isChecked)
        $selectedRow.css({
            "background-color" : "DarkSlateBlue",
            "color" : "GhostWhite"
        });
    else
       $selectedRow.css({
            "background-color" : sColor,
            "color" : "black"
        });
    

So putting it together the complete jQuery code is,

$(document).ready(function() 
{
  $('#<%=gdRows.ClientID%>')
     .find('input:checkbox[id$="chkDelete"]').click(function()
     {
        var isChecked = $(this).prop("checked");
        var $selectedRow = $(this).parent("td").parent("tr");
        var selectedIndex = $selectedRow[0].rowIndex;
        var sColor = '';
            
        if(selectedIndex%2 == 0)
            sColor = 'PaleGoldenrod';
        else
            sColor = 'LightGoldenrodYellow';
                
        if(isChecked)
            $selectedRow.css({
                "background-color" : "DarkSlateBlue",
                "color" : "GhostWhite"
            });
        else
           $selectedRow.css({
               "background-color" : sColor,
               "color" : "black"
          });
    });     
});

See result below

Feel free to contact me for any help related to jQuery, I will gladly help you.



Responsive Menu
Add more content here...