tags:

views:

27

answers:

1

i have a table with 3 columns and i need to get the sum of the values in the second coloumn I am keeping an ID which is used to identify cells of addition. I need to do it in J query ?I would like to know how I can able to acess each rows and colums of a table using for loop.

<table><tr><td>ID</td><td>Mark</td>
<tr><td>1</td><td>40</td></tr>
<tr><td>2</td><td>35</td></tr>
<tr><td>1</td><td>52</td></tr>
</table>

Can I able to access each rows using some indexes like #tbl[row][col] etc .Thnaks In Advance I NEED TO ADD THE VALUES WHERE ID WILL BE ONE THAT IS EXPECTED OUTPUT IS 92[40+52]

+2  A: 

Something like this would work:

​function getTotal(id) {
  var total = 0;
  $("td:first-child").filter(function() { return this.innerHTML == id; })
      .next().each(function() { total += parseInt(this.innerHTML, 10); });
  return total;           
}

For example:

alert(getTotal(1)); // alerts 92
alert(getTotal(2)); // alerts 35

You can test it out here., what this does is get the first columns of cells, does a .filter() down to those that match the ID (don't use :contains() here, it's a substring match) then for the matches, get the neighboring cell using .next(). For those cells we're just using praseInt() to get the number and add it to the total.

Nick Craver
@Nick thanks for ur answer .But i need to change the ID in to last.How can i access the last column.Similar condition.But that column's style is set to display:none
Vishnu K B
@Hari - I'm not following, you want to update the last column of *each* of those rows with the total?
Nick Craver
@Thanks Nick :) I changed some code and made it works Thanks
Vishnu K B
@Nick No wat I need is already done by u.Thanks a lot
Vishnu K B
@Hari - ah ok, just make sure you're all set :)
Nick Craver