Sum total for column in jQuery

The following code isn't working. I need to sum all by column as you can see on jsfiddle. What's going wrong?

HTML

<table id="sum_table" width="300" border="1">
    <tr>
        <td>Apple</td>
        <td>Orange</td>
        <td>Watermelon</td>
    </tr>
    <tr>
        <td class="rowDataSd">1</td>
        <td class="rowDataSd">2</td>
        <td class="rowDataSd">3</td>
    </tr>
    <tr>
        <td class="rowDataSd">1</td>
        <td class="rowDataSd">2</td>
        <td class="rowDataSd">3</td>
    </tr>
    <tr>
        <td class="rowDataSd">1</td>
        <td class="rowDataSd">2</td>
        <td class="rowDataSd">3</td>
    </tr>
    <tr class="totalColumn">
        <td class="totalCol">Total:</td>
        <td class="totalCol">Total:</td>
        <td class="totalCol">Total:</td>
    </tr>
</table>

Javascript

$(document).ready(function(){


   $(".rowDataSd").each(function() {
      newSum.call(this);
    });

});


function newSum() {
    var $table = $(this).closest('table');
    var total = 0;

    $(this).attr('class').match(/(\d+)/)[1];

$table.find('tr:not(.totalColumn) .rowDataSd').each(function()  {
        total += parseInt($(this).html());

});

$table.find('.totalColumn td:nth-child('')').html(total);
}

Answers:

Answer

Here is a jsffile. hope this helps

  <table id="sum_table" width="300" border="1">
        <tr class="titlerow">
            <td>Apple</td>
            <td>Orange</td>
            <td>Watermelon</td>
        </tr>
        <tr>
            <td class="rowDataSd">1</td>
            <td class="rowDataSd">2</td>
            <td class="rowDataSd">3</td>
        </tr>
        <tr>
            <td class="rowDataSd">1</td>
            <td class="rowDataSd">2</td>
            <td class="rowDataSd">3</td>
        </tr>
        <tr>
            <td class="rowDataSd">1</td>
            <td class="rowDataSd">5</td>
            <td class="rowDataSd">3</td>
        </tr>
        <tr class="totalColumn">
            <td class="totalCol">Total:</td>
            <td class="totalCol">Total:</td>
            <td class="totalCol">Total:</td>
        </tr>
    </table> 
<script>
       var totals=[0,0,0];
        $(document).ready(function(){

            var $dataRows=$("#sum_table tr:not('.totalColumn, .titlerow')");

            $dataRows.each(function() {
                $(this).find('.rowDataSd').each(function(i){        
                    totals[i]+=parseInt( $(this).html());
                });
            });
            $("#sum_table td.totalCol").each(function(i){  
                $(this).html("total:"+totals[i]);
            });

        });
</script>
Answer

jsFiddle with example

To achieve this, we can take full advantage of the thead and tfoot tags within the table element. With minor changes, we have the following:

HTML

<table id="sum_table" width="300" border="1">
    <thead>                
        <tr>
            <th>Apple</th>
            <th>Orange</th>
            <th>Watermelon</th>
        </tr>
    </thead>
    <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
    </tr>
    <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
    </tr>
    <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
    </tr>
    <tfoot>
        <tr>
            <td>Total:</td>
            <td>Total:</td>
            <td>Total:</td>
        </tr>
    </tfoot>
</table>???????????????

This then allows us to target more specifically the elements we want, i.e. how many columns are there, and what is the "total" cell.

JavaScript

$(document).ready(function()
{
    $('table thead th').each(function(i)
    {
        calculateColumn(i);
    });
});

function calculateColumn(index)
{
    var total = 0;
    $('table tr').each(function()
    {
        var value = parseInt($('td', this).eq(index).text());
        if (!isNaN(value))
        {
            total += value;
        }
    });

    $('table tfoot td').eq(index).text('Total: ' + total);
}?
Answer
$('#sum_table tr:first td').each(function(){
   var $td = $(this); 

    var colTotal = 0;
    $('#sum_table tr:not(:first,.totalColumn)').each(function(){
        colTotal  += parseInt($(this).children().eq($td.index()).html(),10);
    });

    $('#sum_table tr.totalColumn').children().eq($td.index()).html('Total: ' + colTotal);
});

Live example: http://jsfiddle.net/unKDk/7/

Answer

An alternate way:

$(document).ready(function(){   
    for (i=0;i<$('#sum_table tr:eq(0) td').length;i++) {
       var total = 0;
        $('td.rowDataSd:eq(' + i + ')', 'tr').each(function(i) {
           total = total + parseInt($(this).text());
        });            
        $('#sum_table tr:last td').eq(i).text(total);
    }

});

Example: http://jsfiddle.net/lucuma/unKDk/10/

Answer

This is easily accomplished with a little tweaking of the classes on your table:

HTML:

<table id="sum_table" width="300" border="1">
    <tr>
        <td>Apple</td>
        <td>Orange</td>
        <td>Watermelon</td>
    </tr>
    <tr>
        <td class="col1">1</td>
        <td class="col2">2</td>
        <td class="col3">3</td>
    </tr>
    <tr>
        <td class="col1">1</td>
        <td class="col2">2</td>
        <td class="col3">3</td>
    </tr>
    <tr>
        <td class="col1">1</td>
        <td class="col2">2</td>
        <td class="col3">3</td>
    </tr>
    <tr>
        <td class="total">Total:</td>
        <td class="total">Total:</td>
        <td class="total">Total:</td>
    </tr>
</table>?

JS:

var getSum = function (colNumber) {
    var sum = 0;
    var selector = '.col' + colNumber;

    $('#sum_table').find(selector).each(function (index, element) {
        sum += parseInt($(element).text());
    });  

    return sum;        
};

$('#sum_table').find('.total').each(function (index, element) {
    $(this).text('Total: ' + getSum(index + 1)); 
});

http://jsfiddle.net/unKDk/9/

Answer

I know this has been well answered by now, but I started working on this solution earlier before all the answers came through and wanted to go ahead and post it.

This solution works with the HTML as you posted it, and assumes 4 things: 1) the first row is the header row, 2) the last row is the totals row, 3) each row has equal columns, and 4) the columns contain integers. In this case, only the table needs to be identified.

$(document).ready(function(){
    totalRows("#sum_table");
});

function totalRows(tableSelector) {
    var table = $(tableSelector);
    var rows = table.find("tr");
    var val, totals = [];

    //loop through the rows getting values in the rowDataSd columns
    rows
        .each(function(rIndex) {
            if (rIndex > 0 && rIndex < (rows.length-1)) { //not first or last row
                //loop through the columns
                $(this).find("td").each(function(cIndex) {
                    val = parseInt($(this).html());
                    (totals.length>cIndex) ? totals[cIndex]+=val : totals.push(val);
                });
            }
        })
        .last().find("td").each(function(index) {
            val = (totals.length>index) ? totals[index] : 0;
            $(this).html( "Total: " + val );
        });
}
?
?
Answer

Here you go sir! http://jsfiddle.net/47VDK/

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.