jQuery Conditional Formatting
The jQuery contains and not functions are great for doing conditional formatting. Along with the power of chaining in jQuery you can easily change the look of something in the browser window through a simple jQuery call.
For example, suppose you have a grid view and you are grouping by a certain column and you need each group to total 100% in one of its columns. (Note: I am not going into detail of which grid view control you use.) You could do these 2 lines of code:
- $(”tr[type=TotalRow]:contains(’100.00%’)”).addClass(”Valid”);
- $(”tr[type=TotalRow]:not(:contains(’100.00%’))”).addClass(”Invalid”);
- $(”tr[type=TotalRow] - This will select all table rows that have an attribute named type which has a value of TotalRow.
- :contains(’100.00%’)”) - This will further filter the list of table rows returned by ensuring that they have the text ‘100.00%’ in them.
- .addClass(”Valid”); - This adds a CSS class of name ‘Valid’ to every table row that met the criteria. In this case, every table row that has an attribute named type and a value of TotalRow as well as having the text 100.00% will have the ‘Valid’ CSS class applied to it.
The second line of code simply uses the not function so that it finds any table row that IS of type TotalRow and that does NOT have 100.00% in the row somewhere and then adds a CSS class named Invalid.
Pretty simple and easy to do.