tags:

views:

27

answers:

2

I'm trying to determine how to calculate the difference between successive table cells in jQuery. I have a table that looks like this.

<table id ="tbl">
  <tr>
    <td>5</td>
    <td>12</td>
    <td>15</td>
    <td>17</td>
  </tr>
  <tr>
    <td>3</td>
    <td>6</td>
    <td>12</td>
    <td>13</td>
  </tr>
</table>

I'd like to subtract the first td from the second td (12 - 5), the third from the second (15 - 12), the fourth from the third (17 - 15) etc. I need to do this for every row in the table. I'm sure the answer is simple, but I'm stuck. I know I'll need to loop through each row, but how can I efficiently make this calculation?

$('#tbl tr').each(function(){
  // help!
)}
A: 

Hi,

try this

$(function() {
    $("#tbl tr").each(function() {
        var $currentTr = $(this),
            totalRow = new Array(),
            result = 0;

        $currentTr.find("td").each(function() {
            totalRow.push( parseInt( $(this).html(), 10) );
        });

        result = parseInt( totalRow[0], 10);

        for(var i = 1; i < totalRow.length; i++)
        {
            result -= parseInt(totalRow[ i ], 10);
        }

        //result = Current TR's result
    });
});
Cybrix
Hmm.. finally its not really what are you are looking for... give me a moment
Cybrix
+1  A: 

.prev() and :gt() are your friends.

Iterate over each tr and look at all the tds with an index of greater than zero (the seoncd td and on in each tr). Take that td and subtract the .prev() td to get your answer.

Here's how I'd put the results in a div called results:

$(function() {
    var index = 0;
    $("#tbl tr").find("td:gt(0)").each(function() {
        $this = $(this);
        $("#results").append(++index + ": " + 
                             ($this.html() - $this.prev().html()) + 
                             "<br/>");
    }) 
});

Try it out with this jsFiddle

To be more sure of things, you can use parseInt like this:

    // You can use parseInt to make sure it's an int. Don't forget the radix!
(parseInt($this.html(), 10) - parseInt($this.prev().html(), 10))
Peter Ajtai
this was exactly what I needed. Thank you!
jktress
I'm getting several digits after the decimal place, and thought toFixed(2) on each parseInt (or parseFloat) would solve my problem, however it doesn't seem to be picking it up. Any suggestions?
jktress
@jktress - Well, integers do not have decimal places. If the numbers in your cells have decimals (e.g. `5.2`, then you cannot use `parseInt()`) Take a look at [ **the MDC references for `.parseFloat()` and `.parseInt()`** ](https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#parseInt_and_parseFloat_Functions). You can just use [ **`.parseFloat()`** ](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseFloat) in combination with [ **`.toFixed()`** ](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number/toFixed).
Peter Ajtai