Andrew Jackson
Andrew Jackson

Reputation: 11

if else with 2 text variables

I have two variables in a table.

<table>
<tr>
<td class="cell1">10</td><td class="cell2">5</td>
</tr>
</table>

Now i would like to say, if the number in .cell2 is smaller than the number in .cell1 change the color of .cell2 red.

Upvotes: 0

Views: 207

Answers (3)

Jon
Jon

Reputation: 437366

Fetch the contents of each cell with .text. Convert to numbers with parseInt or parseFloat, and add or remove some CSS class that applies the requisite style conditionally with .toggleClass:

var isSmaller=parseInt($(".cell2").text(),10) < parseInt($(".cell1").text(),10);
$(".cell2").toggleClass("red", isSmaller);

In this example I 'm assuming this additional CSS:

.red { background-color: red }

Upvotes: 5

lzdt
lzdt

Reputation: 499

Here is a fiddle and the relevenat part:

function doStuff() {
   var $v1 = $('.cell1').text();
   var $v2 = $('.cell2').text();   

   /* debug output */
   $('#result').text("result: v1: " + $v1 + ", v2: " + $v2);

   if (parseInt($v1, 10) > parseInt($v2, 10)) {
       $('.cell2').css("background-color", "red");

       /* debug output */
       $('#result').append("</br> cell1 > cell2 == true");
    }        
}

$(document).ready(function() {
    doStuff();
 });

Upvotes: 0

Bill
Bill

Reputation: 413

You could get the string value of the inner text using the text() operator:

cell10 = $('.cell10').text();
cell2  = $('.cell2').text();

Then use the parseInt function:

if (parseInt(cell10) > parseInt(cell2)) {
    ...
}

EDIT Jon beat me to it

Upvotes: 1

Related Questions