Created
March 7, 2014 16:26
-
-
Save westonwatson/9414678 to your computer and use it in GitHub Desktop.
Count Table Column Values
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function tableColumnTotal(tableClassName,columnClassName){ | |
var columnIndexes = []; | |
var columnTotals = []; | |
//grab all tables | |
var tablesToInspect = document.getElementsByClassName(tableClassName); | |
//if tables found | |
if (tablesToInspect.length > 0){ | |
//loop thru tables | |
for (var xIndex=0;xIndex<tablesToInspect.length;xIndex++){ | |
//grab TR/rows | |
var thisTablesRows = tablesToInspect[xIndex].getElementsByTagName('tr'); | |
//loop thru TR/rows | |
if (thisTablesRows.length > 0) for (var yIndex=0;yIndex<thisTablesRows.length;yIndex++){ | |
//grab all td/Columns | |
var thisRowsColumns = thisTablesRows[yIndex].getElementsByTagName('td'); | |
//loop thru columns/td | |
if (thisRowsColumns.length > 0) for (var zIndex=0;zIndex<thisRowsColumns.length;zIndex++){ | |
//grab Column | |
var thisColumn = thisRowsColumns[zIndex]; | |
//look for classname | |
if (thisColumn.className.indexOf(columnClassName)>-1) { | |
//set column index to countable | |
columnIndexes[zIndex] = true; | |
columnTotals[zIndex] = 0; | |
}else if(columnIndexes[zIndex]){ | |
//add value to Totals | |
columnTotals[zIndex] += parseInt(thisColumn.innerText); | |
}else{ | |
//nothing | |
} | |
} | |
} | |
//create a new Table row with totals | |
var newTableRow = document.createElement('tr'); | |
newTableRow.className ="tablehdr"; | |
//loop thru columns | |
if (thisRowsColumns.length > 0) for(var vIndex=0;vIndex<thisRowsColumns.length;vIndex++){ | |
var newColumn = document.createElement('td'); | |
newColumn.innerHTML = (vIndex in columnIndexes) ? columnTotals[vIndex] : " "; | |
newColumn.align = "center"; | |
newTableRow.appendChild(newColumn); | |
} | |
//attach totals row to Table | |
tablesToInspect[xIndex].appendChild(newTableRow); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment