...

View Full Version : Creating array from table column



carlton
02-22-2007, 07:42 PM
Hey guys

I'm writing an app for my school's site that will make an excel-like spreadsheet in which someone can type how many credits they have in science, etc...

My problem is that I'm not sure how to store the numeric values of a table column in an array to add them up (in order to calculate the total science credits, for example). I really don't want to make individual IDs for 160 table cells and add them individually :eek:

Could someone point me in the right direction on how to get all of the TDs in a table row in an array?

Thanks,
Carlton

shyam
02-22-2007, 08:11 PM
tds = tr.getElemensByTagName('td');
the only problem will be this will fetch all the tds even td's of the tables nested in this tr so its a good practise to filter out those


function getTDs(tr) {
var tds = tr.getElementsByTagName('td');
target = [];
for ( i = 0; i < tds.length; i++ ) {
if ( tds[i].parentNode == tr ) {
target.push(tds[i]);
}
}
return target;
}

but, its generally an overkill

Arbitrator
02-22-2007, 08:13 PM
getElementsByTagName() returns an array of matching elements. Example:

var sum = 0, tableCells = document.getElementsByTagName("td");

for (var i = 0; i < tableCells.length; i++) {
sum += parseFloat(document.getElementsByTagName("td")[i].firstChild.data);
}
This script iterates through every td element in the document and adds their content together. firstChild.data is the text node child of the cell; you need to convert it to a number before you can use it.

Note: shyam beat me to the post.

ccemmett
02-25-2007, 05:20 PM
Give the table containing the credits an ID like "credits"



var totals = new Array()

function credCount() {
var rows=document.getElementById("credits").getElementsByTagName("tr")
for(i=0;i<rows.length;i++){
var cols=rows[i].getElementsByTagName("td")
for(j=0;j<cols.length;j++){
if(isNaN(totals[j])){
totals[j]=0
}
totals[j]=parseInt(cols[j].innerHTML,10)+totals[j]
}
}
// Do something with the totals
}


Total as many columns as you like.

CC



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum