Reputation: 1623
I am learning jQuery atm and can't find my error here... actually the "problem" is quite simple
if a td cell with the class "red" has a value > 50, make it red
the jQuery code
$(document).ready(function(){
var n = $(".red").val();
if (n > 50) {
$(".red").css("color", "red");
}
else {
$(".red").css("color", "blue");
}
});
do i have to use .each() here?
Upvotes: 1
Views: 1823
Reputation: 1220
This should do it...
Live demo: Fiddle
<table id="theTable" border="1">
<tr>
<td class="red">5</td><td class="red">25</td><td class="red">50</td><td class="red">51</td><td class="notRed">105</td>
</tr>
</table>
$(document).ready(function(){
$('#theTable td.red').each(function(){
var cellVal = parseInt($(this).text())
if(cellVal > 50)
$(this).css("background-color","red");
else
$(this).css("background-color","blue");
});
});
Upvotes: 0
Reputation: 55750
Firstly td
elements do not have the val
property.
Need to use .text
to get the text
Next use parseInt to convert it to a number
if (n > 50) {
supposed to b e
if (parseInt(n, 10) > 50) {
But because you are specifically setting each td
to a specific color. You need to iterate over the list using $.each
. You can also use .filter
as well.
// Will return all the `tds` with the value
var $red = $('.red').filter(function() {
return parseInt( $(this).text(), 10) > 50;
});
// Set the red elements to color red
$red.css('color', 'red');
// All `.red` which are not in above selector are selected
$('.red').not($red).css('color', 'blue');
Upvotes: 1