How to dynamically calculate the total of each column in a table on an HTML page?

advertisements

I will basically have a table with days of the week (header row across). Column 1-Sunday, Column 2-Monday, etc. Each cell will be entered with hours worked, i.e., 8. The last row I want each cell to dynamically calculate the total of the cells above it in its column, after the data is entered into each cell. Ideally, this should be calculated after moving the cursor to a different cell.

It seems like I should use some JavaScript for this. But I can't write JavaScript from scratch; I can only tweak it to what I need after it's been written.

For our purposes here's a basic table. I'll put examples in Column 1.

<table id="workweek" class="wwtable">
<tr><th>sunday</th><th>monday</th><th>tuesday</th><th>wednesday</th><th>thursday</th><th>friday</th><th>saturday</th></tr>
<tr><td>8 </td><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td></tr>
<tr><td>8 </td><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td></tr>
<tr><td>8 </td><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td></tr>
<tr><td>8 </td><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td></tr>
<tr><td>8 </td><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td></tr>
<tr><td>(Calculate 40 here) </td><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td></tr>
</table>

Forgot to mention. Each cell will have the user input the hours for each day, so there will be input fields in each cell.


If jQuery is a viable option for you, you can iterate through all td in a given column like this:

$('#workweek>tbody>tr>td:nth-child(1)').each( function(){
    sum += parseInt($(this).text()) || 0;
});

I've put together a working example for you on jsFiddle:

for (var i=1; i<8; i++)
{
    var sum = 0;

    // iteration through all td's in the column
    $('#workweek>tbody>tr>td:nth-child(' + i + ')').each( function(){
        sum += parseInt($(this).text()) || 0;
    });

    // set total in last cell of the column
    $('#workweek>tbody>tr>td:nth-child(' + i + ')').last().html(sum);
}

Be aware that this example will erase the content of the last cell of the column if it's not empty.