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:
Define a style sheet class which will be used to highlight negative column value.
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.
Related Post:
- jQuery.isNumeric in jQuery 1.7
- Download ASP.NET GridView & jQuery Tips and Tricks eBook PDF
- Common jQuery Mistakes
How to do it?
Define a style sheet class which will be used to highlight negative column value.
1 | .negative |
2 | { |
3 | font-weight: bold; |
4 | color:red; |
5 | } |
- 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.
01 | $(document).ready( function () { |
02 | $( "#<%=gdRows.ClientID%> tr:has(td)" ).each( function () { |
03 | var $tdElement = $( this ).find( "td:eq(2)" ); //Cache Quantity column. |
04 | var cellText = $tdElement.text(); |
05 | if ($.isNumeric(cellText)) |
06 | { |
07 | var iNum = parseInt(cellText); |
08 | if (iNum < 0) |
09 | $tdElement.addClass( 'negative' ); |
10 | } |
11 | }); |
12 | }); |
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.
01 | $(document).ready( function () { |
02 | $( "#<%=gdRows.ClientID%> td" ).each( function () { |
03 | var cellText = $( this ).text(); |
04 | if ($.isNumeric(cellText)) |
05 | { |
06 | var iNum = parseInt(cellText); |
07 | if (iNum < 0) |
08 | $tdElement.addClass( 'negative' ); |
09 | } |
10 | }); |
11 | }); |