The table should probably look more like this:
<table> <thead> <tr><th>Faculty (Subject)</th><th>Student 2013</th><th>Student 2014</th></tr> </thead> <tbody id="sdtable"> <tr><th>Business</th><td>12922</td><td>11420</td></tr> <tr><th>Earth Sciences</th><td>4320</td><td>4611</td></tr> <tr><th>Education</th><td>14560</td><td>13490</td></tr> ... </tbody> <tfoot> <tr><th>Totals:</th><th></th><th></th></tr> </table>
to separate the header, body, and footer into separate sections of the table. The function should be as follows:
function calculate(){ // Get a reference to the tBody var tBody = document.getElementById('sdtable'); if (!tBody) return; var row, rows = tBody.rows; var cell, cells; var cellTotals = {}; // For each row in the body for (i=0, iLen=rows.length; i<iLen; i++) { row = rows[i]; cells = row.cells; // Add the cells in each column, starting on the second column // ie starting with cell index 1 for (var j=1, jLen=cells.length; j<jLen; j++) { cell = cells[j]; if (j in cellTotals) { cellTotals[j] += Number(cell.textContent || cell.innerText); } else { cellTotals[j] = Number(cell.innerHTML); } } } // Write the totals into the footer var tFoot = tBody.parentNode.tFoot; row = tFoot.rows[0]; for (var k=1; k<jLen; k++) { row.cells[k].innerHTML = cellTotals[k]; } }
Note that by convention, variables with a name starting with a capital letter are reserved for constructors (although constants are usually all caps).
source share