How to dynamically calculate the total of each col

2020-07-25 10:40发布

问题:

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.

回答1:

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.



回答2:

You can loop through the DOM of the table, and get the textContent or innerText of each cell as the value in hours.

This is a popular way to do it:

function strip(html) {
    var tmp = document.createElement("DIV");
    tmp.innerHTML = html;
    return tmp.textContent||tmp.innerText;
}

Then (something like this): Working example: http://jsfiddle.net/7srJf/3/

var tbl = document.getElementById('my-table');
var rows = tbl.rows;
var DAYS_OF_WEEK = 2, totals = [0, 0];
for (var i = 0; i < DAYS_OF_WEEK; i++) { 
    for (var j = 1; j < rows.length; j++) {
      var cell = rows[j].cells[i];
      var numHours = parseInt(strip(cell.innerHTML), 10);
      totals[i] += numHours;
    }
}