How to add values ​​to a table together using jQuery?

I have an HTML table with numbers. I need to do this to get all these values ​​and add them together using jQuery.

Any ideas?


Example table:

http://pastie.org/998759

+3
source share
3 answers

You can call .each:

var sum = 0;

$('table td').each(function() {
    sum += parseFloat($(this).text());
});
+2
source

I am going to give you some pseudo-code, how I would do it (mainly because I cannot be started writing all of this).

  • Create an object / array / variables to store the totals.
  • jQuery select table
  • Use .each()to scroll through each tr.
  • td .
  • , tr , , :)

, :)

EDIT: , , .

+1

This has already been answered. So, as a fun exercise:

// Give all arrays the power of summation    
Array.prototype.sum = function(){
    for( var i=0,sum=0;i<this.length;sum+=this[i++] );
    return sum;
}

// Use map for kicks
$(document).ready( function(){
    var result = $('table#mytable tr td').map( function(){
        return parseFloat( $(this).text() );
    }).get().sum();
});
+1
source

Source: https://habr.com/ru/post/1749318/


All Articles