What I've managed to do so far is use the following code (example, not the actual code):
<script>
function startCalc(){
interval = setInterval("calc()",1);
}
function calc(){
one = document.autoSumForm.firstBox.value;
two = document.autoSumForm.secondBox.value;
document.autoSumForm.thirdBox.value = (one * 1) + (two * 1);
}
function stopCalc(){
clearInterval(interval);
}
</script
It works like a charm, but for that many boxes it's just too much code and whenever I have to add new boxes, it's too much work.
I've tried different ways to loop through the boxes, but none of the codes I've compiled seems to do the trick. I have now spent too many hours on this, and I need help. Please?
This calculates the sums for each row and each column. It uses a button to calculate the totals whenever you click it. You can easily convert the button to a setInterval but set the interval to at least 1/2 second if not more if the number of cells is relatively large. You have it set to 1/1000 sec. I haven't calculated the total sum though. That is easily added in.
You can add as many rows or colums as you like without having to change the js code. The only assumption the code makes is that the last cell in each row is the totoal for that row and that the last row of cells is the totals for each column.
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
function calcTotals() {
var rowTot=0;
for(i=0; i < colTotals.length; i++){
colTotals[i].value = 0;
}
for(i=0; i < numRows-1; i++) {
for(j=0; j < numCols-1; j++){
rowTot += new Number(cellsO[i][j].value);
colTotals[j].value = new Number(colTotals[j].value)+ new Number(cellsO[i][j].value);
}
rowTotals[i].value= rowTot;
rowTot = 0;
}
}
window.onload=function(){
var cellContO = document.getElementById('cellContainer');
var cellContDivsO = cellContO.getElementsByTagName('div');
numRows = cellContDivsO.length;
numCols = cellContDivsO[0].getElementsByTagName('input').length;
//get the data cells
cellsO = new Array(); //2D array
rowTotals = new Array();
colTotals = new Array();
for(i=0; i < numRows; i++){
rowCells = cellContDivsO[i].getElementsByTagName('input');
if(i < numRows-1){
cellsO[i] = new Array();
for(j=0; j < numCols; j++){
if(j < numCols-1){
cellsO[i][j] = rowCells[j];
} else {
rowTotals[i] = rowCells[j]
}
}
} else {
colTotals = rowCells;
}
}
document.getElementById('btnCalcTotals').onclick=calcTotals;
}
</script>
</head>
<body>
<div id="cellContainer">
<div><input type="text" /><input type="text" /><input type="text" /></div>
<div><input type="text" /><input type="text" /><input type="text" /></div>
<div><input type="text" /><input type="text" /><input type="text" /></div>
<div><input type="text" /><input type="text" /><input type="text" /></div>
</div>
<button id="btnCalcTotals">Calculate totals</button>
</body>
</html>
Bookmarks