Jquery, Web

Colorize negative number using jquery in html table


Recently I was working on creating reports for clients on web portal. We are developing web portabl in asp.net MVC3 and using jquery utility functions.

One of the UI requirement was to colorize negative numbers. I can implement in server side in chtml pages but it would not be generic for all pages. So I decided to use jquery functions to do this task.

This is my html page:

<table class=”list”>
<tr>
<td>Date</td>
<td class=”right”>Amount</td>
</tr>
<tr>
<td>2012-05-01</td>
<td class=”right”>-5.156</td>
</tr>
<tr>
<td>2012-05-01</td>
<td class=”right”>-8.25</td>
</tr>

<tr>
<td>2012-05-01</td>
<td class=”right”>55.45</td>
</tr>
</table>​

Date Amount
2012-05-01 -5.156
2012-05-01 -8.25
2012-05-01 55.45

Java Script
On Dom Ready

$(function(){

$(“td.right”).filter(function() {
return $.trim($(this).text()).indexOf(“-“) == 0;
}).addClass(“negative”)​;
});

Css
.right
{
text-align:right;
}
.left
{
text-align:left;
}
.negative
{
color:red;
text-align:right;
}

.list
{
border: 1px solid;
}
.row
{
border: 1px solid;
}

Jquery filter function applied on td element which has class name “right”. this function find index of ‘-‘ and if it on first place it will return true. In case of true, css class “negative” will be applied to td tag.

we can also use contains functions to applied color.

$("td.right"):contains('-').addClass("negative");

Problem with this approach is it will apply negative class to any value which contains ‘-‘ on any place.

You can see live example at JFiddle.

http://jsfiddle.net/neerajkaushik_123/AwCqz/3/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s