Reputation: 335
Scenario: I have a table with about 10 rows, each containing a of class '.t3_dc'.
These cells will contain a value of between 1.0 and 9.9
For each td, I want to check if the score/value is between a certain amount and if so, change the colour. For example, < 7.0 would be red, 7-8 stay white, above 8 would be green.
I got this far after a few attempts but my biggest obstacle seems to be storing each into an array and then running through and checking them individually.
$(document).ready( function() {
function scores () {
var score = $('td.t3_dc').text();
var num = parseFloat(score);
alert(score)[0];
if(num < 7 ) {
$(score).css('color','green');
}
else {
$(score).css('color','red');
}
};
setTimeout(scores, 2000);
});
Note: The timeout function exists as the table itself takes a couple of seconds to load on the page
Q. How can I loop through an array of 's and check each value, adding a colour as necessary?
Upvotes: 1
Views: 101
Reputation: 5745
use $.each
for loop into yours elements. try
$(document).ready( function() {
function scores () {
$.each($('td.t3_dc'),function(){
if(parseFloat($(this).text()) < 7 ) {
$(this).css('color','green');
}
else {
$(this).css('color','red');
}
});
};
setTimeout(scores, 2000);
})
Upvotes: 1
Reputation: 18113
Imho, you don't need a timeout, the function will first fire when the page is loaded. Then loop the classes by using each()
and check it's value.
$(function() {
$('.t3_dc').each( function() {
var elem = $(this) ,
value = parseFloat( elem.text() );
if( value < 7 ) {
elem.css('color', 'red');
}
elseif( value > 8 ) {
elem.css('color', 'green');
}
});
});
Upvotes: 2