Wednesday, March 16, 2011


<script type="text/javascript">
window.onload=function() {
var sum = 0;

var dataTable = document.getElementById("table1");
//use querySelector to find all second table cells
var cells = document.querySelectorAll("td + td");

for (var i = 0; i < cells.length; i++) {
sum+=parseFloat(cells[i].firstChild.data);
}
//now add sum to end of table
var newRow = document.createElement("tr");

//first cell
var firstCell = document.createElement("td");
var firstCellText = document.createTextNode("Sum:");
firstCell.appendChild(firstCellText);
newRow.appendChild(firstCell);
//second row with sum
var secondCell = document.createElement("td");
var secondCellText = document.createTextNode(sum);
secondCell.appendChild(secondCellText);
newRow.appendChild(secondCell);


//add row to table
dataTable.appendChild(newRow);

}
</script>

1 comment:

Brad Jensen said...

This is pretty cool - adding the data in an array and then posting the sum back.

Javascipt would make me want a really good DOM (document Object Model) explorer to find the way to access all the elements of the docment.