jktress
jktress

Reputation: 1097

jQuery subtracting successive table cells

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!
)}

Upvotes: 1

Views: 676

Answers (2)

Peter Ajtai
Peter Ajtai

Reputation: 57695

.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))

Upvotes: 1

Cybrix
Cybrix

Reputation: 3318

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
    });
});

Upvotes: 0

Related Questions