Highlight Negative value columns in ASP.NET GridView using jQuery

In this post, find jQuery code to highlight negative value columns/cells in ASP.NET GridView. This is a helpful feature as it draws user's attention immediately and informs him that there is something wrong with some of the entities.

Related Post:

How to do it?

Define a style sheet class which will be used to highlight negative column value.

.negative
{
   font-weight: bold;
   color:red;
}
  • Iterate through all tr elements and select column which may have negative values. For demo, Quantity column is selected.
  • Cache the required column and check it's text. If text is numeric and less than 0 then apply style sheet to it.

So putting it together the complete jQuery code is,

$(document).ready(function () {
  $("#<%=gdRows.ClientID%> tr:has(td)").each(function () {
    var $tdElement = $(this).find("td:eq(2)"); //Cache Quantity column.
    var cellText = $tdElement.text();
    if ($.isNumeric(cellText)) 
    {
       var iNum = parseInt(cellText);
       if (iNum < 0) 
          $tdElement.addClass('negative');
    }
  });
});

Now, the above jQuery code is specific to a column and what if there are multiple columns which may contain negative values and you want to highlight them as well then above code will not work. The generic solution will be to iterate through all columns and see if they are negative. If yes, then highlight them.

$(document).ready(function () {
  $("#<%=gdRows.ClientID%> td").each(function () {
      var cellText = $(this).text();
      if ($.isNumeric(cellText)) 
      {
         var iNum = parseInt(cellText);
         if (iNum < 0) 
            $tdElement.addClass('negative');
      }
  });
});

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



Responsive Menu
Add more content here...