How to Add values in a table together using jQuery?

故事扮演 提交于 2019-12-04 13:03:48

You can call .each:

var sum = 0;

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

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.

It's already been answered. So just 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();
});
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!