I'd like to color numbers in a table for better readability:
green for positive (+00.00); red for negative (-00.00) and; black for default case (no sign)
Many thanks!
I'd like to color numbers in a table for better readability:
green for positive (+00.00); red for negative (-00.00) and; black for default case (no sign)
Many thanks!
Firstly, the best way to do this if the numbers are static is on the serverside. Assign a class based on value:
<td class="positive">+34</td>
<td class-"negative">-33</td>
with:
td { color: black; }
td.positive { color: green; }
td.negative { color: red; }
(or be more selective if you need to be).
But if you must do this on the client, I might suggest:
$("td").each(function() {
var text = $(this).text();
if (/[+-]?\d+(\.\d+)?/.test(text)) {
var num = parseFloat(text);
if (num < 0) {
$(this).addClass("negative");
} else if (num > 0) {
$(this).addClass("positive");
}
}
});
You may need to adjust the regular expression depending on what kinds of numbers you want to catch (eg 1.2e11 or 3,456).
Why the regex and not just parseFloat()
? Because:
parseFloat("34 widgets");
returns 34. If this is fine then use that and skip the regex test.
Here ya go:
$(document).ready( function() {
// the following will select all 'td' elements with class "of_number_to_be_evaluated"
// if the TD element has a '-', it will assign a 'red' class, and do the same for green.
$("td.of_number_to_be_evaluated:contains('-')").addClass('red');
$("td.of_number_to_be_evaluated:contains('+')").addClass('green');
}
Then use CSS to style the input elements:
td.red {
color: red;
}
td.green {
color: green;
}
The css:
.pos { color:green; }
.neg { color:red; }
The markup
<table>
<tr><td>+11.11</td><td>-24.88</td><td>00.00</td></tr>
<tr><td>-11.11</td><td>4.88</td><td>+16.00</td></tr>
</table>
The code
$('td').each(function() {
var val = $(this).text(), n = +val;
if (!isNaN(n) && /^\s*[+-]/.test(val)) {
$(this).addClass(val >= 0 ? 'pos' : 'neg')
}
})