0

I have a table like this:

<table id="comparison">
    <tr>
        <th>Hotels</th>
        <th>Jan 2013</th>
        <th>Feb 2013</th>
    </tr>
    <tr>
        <td>Lorem Ipsum Hotel</td>
        <td>
            <div class="rooms">165</div>
            <div class="sob">352</div>
        </td>
        <td>
            <div class="rooms">215</div>
            <div class="sob">30</div>
        </td>
    </tr>
</table>

I prepared this jQuery script to compare the Rooms and SOB in each cell.
- If the SOB is less than the Rooms then I color the SOB red to signal a negative result.
- If the SOB is greater than the Rooms then I color SOB green to signal a positive result.

$('#comparison td .sob').each(function() {
    var rooms = $(this).prev().text();
    var sob = $(this).text();
    if (rooms > sob) {
        $(this).css({'color': 'red'});
    } else {
        $(this).css({'color': 'green'});
    }
});

The problem is that this script is not comparing the Rooms and SOB correctly. It seems to be running at random in the variable comparison, sometimes producing the correct result and other times not.

What am I missing?

Alex
  • 15
  • 3

4 Answers4

2

You're using the text values for comparison, not the numerical value.

Try replacing these two lines:

var rooms = $(this).prev().text();
var sob = $(this).text();

With this:

var rooms = parseInt($(this).prev().text(),10); // always use a radix
var sob = parseInt($(this).text(),10);

On another note, you might want to add the css class in the code that generates your page output if you can (also assuming the HTML content is dynamically-generated, of course).

Blazemonger
  • 90,923
  • 26
  • 142
  • 180
CassOnMars
  • 6,153
  • 2
  • 32
  • 47
0

Try this

$('#comparison td .sob').each(function() {
    var rooms = Number($(this).prev().html());
    var sob = Number($(this).html());
    if (rooms > sob) {
        $(this).css({'color': 'red'});
    } else {
        $(this).css({'color': 'green'});
    }
});
Bhushan Firake
  • 9,338
  • 5
  • 44
  • 79
0

Try this,

var rooms = parseInt($(this).siblings('.rooms').text());
Hauleth
  • 22,873
  • 4
  • 61
  • 112
Sen Jacob
  • 3,384
  • 3
  • 35
  • 61
0

I think you have to parse the text into int:

$('#comparison td .sob').each(function() {
  var rooms = Math.floor($(this).siblings().text());
  var sob = Math.floor($(this).text());
  if (rooms > sob) {
    $(this).css({'color': 'red'});
  } else {
    $(this).css({'color': 'green'});
  }
});

Math.floor(): i read somewhere its quite faster in performace against parstInt()

Jai
  • 74,255
  • 12
  • 74
  • 103