Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Add values in a table together using jQuery?

I have an HTML table with number values. What I need to do is to get all these values and add them together using jQuery.

Any ideas?


Example table:

http://pastie.org/998759

like image 547
Ricky Avatar asked Dec 03 '25 09:12

Ricky


2 Answers

You can call .each:

var sum = 0;

$('table td').each(function() {
    sum += parseFloat($(this).text());
});
like image 196
SLaks Avatar answered Dec 05 '25 01:12

SLaks


I'm going to give you some pseudo-code of how I would do it (mainly because I can't be stuffed writing the whole thing).

  1. Create an object/array/variables to store the totals.
  2. jQuery select the table
  3. Use .each() to loop through each tr.
  4. Loop each td and add the value to the relevant total.
  5. Once all of the tr have been looped through, do whatever you want :)

Hope this helps you out :)

EDIT: I was writing the code as if you wanted to total each column, rather than all cells into a single total.

like image 21
Alastair Pitts Avatar answered Dec 05 '25 00:12

Alastair Pitts



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!