954,157 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Collect sum of a column in a html table?

Hi

This is either really simple or completely impossible :)

I have a table like the following:

<table>
<tr>
<td>1</td>
<td>2</td>
</tr>

<tr>
<td>7</td>
<td>9</td>
</tr>

<tr>
<td><<SUM OF THIS COLUMN (8)>></td>
<td><<SUM OF THIS COLUMN(11)>></td>
</tr>
</table>


I hope you understand what it is im asking. This is easy to do in mysql however can it be done in standard html/dhtml ?

Thanks

Designer_101
Posting Whiz
314 posts since Jul 2007
Reputation Points: 12
Solved Threads: 16
 

you would do the following. Hope it helps.

<html>
    <head>
    </head>
    <body>
        <table id="countit">
            <tr>
                <td class="count-me">12</td>
                <td>Some value</td>
            </tr>
            <tr>
                <td class="count-me">2</td>
                <td>Some value</td>
            </tr>
            <tr>
                <td class="count-me">17</td>
                <td>Some value</td>
            </tr>
        </table>
        <script language="javascript" type="text/javascript">
            var tds = document.getElementById('countit').getElementsByTagName('td');
            var sum = 0;
            for(var i = 0; i < tds.length; i ++) {
                if(tds[i].className == 'count-me') {
                    sum += isNaN(tds[i].innerHTML) ? 0 : parseInt(tds[i].innerHTML);
                }
            }
            document.getElementById('countit').innerHTML += '<tr><td>' + sum + '</td><td>total</td></tr>';
        </script>
    </body>
</html>
Fungus1487
Posting Pro in Training
459 posts since Apr 2007
Reputation Points: 66
Solved Threads: 56
 

101,

The solution depends on why you need to do this?

If you build your table manually, then do the summation manually and type in the HTML for the totals row manually, complete with its values.

If your HTML is pasted from a spreadsheed, then get the spreadsheet to do the totals and paste in the total rows along with the other rows.

If you build the table dynamically, either server-side or client-side, then get the build script to do the summation and write the totals row as per the other rows.

If the values in the table occur in response to some sort of user interaction(s), then OK, use JavaScript to scan the table and write in the totals but that would require the calculation script to be triggered by the user event(s) in question (data entry/button press or whatever) rather than using a "one-off" script embedded in the HTML. Write the code as a javascript function and call it from event handler(s) as appropriate.

Also (from solution above), my IE6 (maybe other browsers) doesn't like document.getElementById('countit').innerHTML += '.....'; . It may work in Moz/Opera, I haven't tested. For me, it's better to add <tr><td id="total_1"></td><td id="total_2"></td></tr> to the bottom of the table (manually if that's how you write your HTML), then populate it from the calculation function. eg something like:

document.getElementById('total_1').innerHTML = sum1;
document.getElementById('total_2').innerHTML = sum2;

This has the added advantage of allowing reuse; the function can be called more than once (per page-session) without adding a growing number total rows to the table, which is important if the purpose of all this is to respond to user events (in the plural).

Apart from that, and with my proviso about reuse, Fungus' script will work if a one-off, in-line calculation is what's required.

Hope this helps

Airshow

Airshow
WiFi Lounge Lizard
Moderator
2,678 posts since Apr 2009
Reputation Points: 321
Solved Threads: 372
 

Thanks for this code. We have used it to calculate Donations to a Public Radio Station in WA, but we have additional rows that we want to ignore (the Check Number). How would that work? Here is the code...

<table id="cbtf_24">
				<tr>
					<td class="titleCell"><label for="68">First Donation $:</label></td>
					<td class="fieldCell" id="68">2</td>

				</tr>
				<tr>
					<td class="titleCell"><label for="69">First Donation Date:</label></td>
					<td class="fieldCell" id="69">01/01/2010</td>
				</tr>
				<tr>
					<td class="titleCell"><label for="cbfv_74">First Check Number:</label></td>
					<td class="fieldCell" id="74">101010</td>
				</tr>
				<tr>
					<td class="titleCell"><label for="75">2nd Donation $:</label></td>
					<td class="fieldCell" id="75">1</td>
				</tr>
				<tr>

					<td class="titleCell"><label for="76">2nd Donation Date:</label></td>
					<td class="fieldCell" id="76">-</td>
				</tr>
				<tr>
					<td class="titleCell"><label for="77">2nd Check Number:</label></td>
					<td class="fieldCell" id="77">-</td>
				</tr>

				<tr>
					<td class="titleCell"><label for="78">3rd Donation $:</label></td>
					<td class="fieldCell" id="78">4</td>
				</tr>
				<tr>
					<td class="titleCell"><label for="79">3rd Donation Date:</label></td>
					<td class="fieldCell" id="79">-</td>

				</tr>
				<tr>
					<td class="titleCell"><label for="80">3rd Check Number:</label></td>
					<td class="fieldCell" id="80">-</td>
				</tr>
				<tr>
					<td class="titleCell"><label for="81">4th Donation $:</label></td>

					<td class="fieldCell" id="81">3</td>
				</tr>
				<tr>
					<td class="titleCell"><label for="82">4th Donation Date:</label></td>
					<td class="fieldCell" id="82">-</td>
				</tr>
				<tr>

					<td class="titleCell"><label for="83">4th Check Number:</label></td>
					<td class="fieldCell" id="83">-</td>
				</tr>
				<tr>
					<td class="titleCell"><label for="84">5th Donation $:</label></td>
					<td class="fieldCell" id="84">99</td>
				</tr>

				<tr>
					<td class="titleCell"><label for="85">5th Donation Date:</label></td>
					<td class="fieldCell" id="85">-</td>
				</tr>
				<tr>
					<td class="titleCell"><label for="86">5th Check Number:</label></td>
					<td class="fieldCell" id="86">-</td>

				</tr>
			</table>

<script language="javascript" type="text/javascript">

var tds = document.getElementById('cbtf_24').getElementsByTagName('td');
var sum = 0;
for(var i = 0; i < tds.length; i ++) {
if(tds[i].className == 'fieldCell') {
sum += isNaN(tds[i].innerHTML) ? 0 : parseInt(tds[i].innerHTML);
}
}
document.getElementById('cbtf_24').innerHTML += '<tr> <td> ' + sum + '</td> <td> total</td> </tr> ';
</script>


As you can tell, the Check Number would be included in the sum, which is obviously not intended. Please keep in mind that the id and class names are created by a content management system and cannot be changed. Is there a way to only parse td's where the previous td contains the text "Donation $" ?

equality4xy
Newbie Poster
4 posts since Jan 2010
Reputation Points: 10
Solved Threads: 0
 
<script>

function totalTable() {
   var arr = document.getElementsByTagName("TD");
   var count1 = 0;
   var count2 = 0;
   for (a = 0; a < arr.length; a++){
       var mytd = arr[a].innerHTML;
       if (isNumeric(mytd, false) == true) {
	       if (arr[a].className == "column1"){
	          count1 = count1 + parseInt(mytd);
		   } else {
		      count2 = count2 + parseInt(mytd);
		   }
	    }
   }
   document.getElementById("total1").innerHTML = "SUM OF THIS COLUMN (" + count1 + ")";
   document.getElementById("total2").innerHTML = "SUM OF THIS COLUMN (" + count2 + ")";
   //alert(count1 + " " + count2);
}
   function isNumeric(sText, decimalAllowed) {
        if (sText.length == 0) return false;
    	var validChars = "";
		if (decimalAllowed) {
			validChars = "0123456789.";
		} else {
			validChars = "0123456789";
		}
        var isNumber = true;
        var charA;
		var decimalCount = 0;
        for (i = 0; i < sText.length && isNumber == true && decimalCount < 2; i++) {
            charA = sText.charAt(i); 
			if (charA == ".") { 
				decimalCount += 1;
			}
            if (validChars.indexOf(charA) == -1) {
               isNumber = false;
            }
        }
        return isNumber;
    }
    window.onload = totalTable;
</script>
harrierdh
Junior Poster in Training
62 posts since Dec 2009
Reputation Points: 10
Solved Threads: 13
 

harrierdh,

Thanks for that but this is a single column output not two columns. Also I am unable to change the class or id parameters because it is part of a CMS.

I need to only parse the sum of certain td tags and not others that are in the same column.

equality4xy
Newbie Poster
4 posts since Jan 2010
Reputation Points: 10
Solved Threads: 0
 

Can you provide a little more info. Do a view source and put that in between [code] tags. Or print screen or link or something. It is hard to visualize what your table looks like with real data. What you are trying to do is completely possible with or without being able to modify id's or name's.

harrierdh
Junior Poster in Training
62 posts since Dec 2009
Reputation Points: 10
Solved Threads: 13
 

Hi there, I agree with everyones comments including creating functions for re-usability yadda yadda yadda, BUT the kid asked how to total up a table using just DHTML.

Here is the revised code to not add the Check Number rows to the sum.

var trs = document.getElementById('cbtf_24').getElementsByTagName('tr');
var sum = 0;

// Loop through each row
for(var k = 0; k < trs.length; k ++) {
    var tds = trs[k].getElementsByTagName('td');
    var lbl = tds[0].getElementsByTagName('label')[0].innerHTML;

    // Check the first column does not contain the word Check Number
    if(lbl.indexOf('Check Number') == -1) {
        sum += isNaN(tds[1].innerHTML) ? 0 : parseInt(tds[1].innerHTML);
    }
}

document.getElementById('cbtf_24').innerHTML += '<tr> <td> ' + sum + '</td> <td> total</td> </tr> ';
Fungus1487
Posting Pro in Training
459 posts since Apr 2007
Reputation Points: 66
Solved Threads: 56
 

this is an alternate method I am trying (but not succeeding) that will give you a good idea what I intend. I need to sum only the rows that have "Donation $" in the 1st column (1st td of the tr). Can anyone tell what I have done wrong? It is not displaying the total at the bottom...

<table class="cbFieldsContentsTab cbFields" id="cbtf_24">
				<tr class="sectiontableentry2 cbft_integer" id="cbfr_68">
					<td class="titleCell"><label for="cbfv_68">First Donation $:</label></td>
					<td class="fieldCell" id="cbfv_68">2</td>
				</tr>
				<tr class="sectiontableentry1 cbft_date" id="cbfr_69">
					<td class="titleCell"><label for="cbfv_69">First Donation Date:</label></td>

					<td class="fieldCell" id="cbfv_69">01/01/2010</td>
				</tr>
				<tr class="sectiontableentry2 cbft_text" id="cbfr_74">
					<td class="titleCell"><label for="cbfv_74">First Check Number:</label></td>
					<td class="fieldCell" id="cbfv_74">101010</td>
				</tr>
				<tr class="sectiontableentry1 cbft_integer" id="cbfr_75">

					<td class="titleCell"><label for="cbfv_75">2nd Donation $:</label></td>
					<td class="fieldCell" id="cbfv_75">1</td>
				</tr>
				<tr class="sectiontableentry2 cbft_date" id="cbfr_76">
					<td class="titleCell"><label for="cbfv_76">2nd Donation Date:</label></td>
					<td class="fieldCell" id="cbfv_76">-</td>
				</tr>

				<tr class="sectiontableentry1 cbft_text" id="cbfr_77">
					<td class="titleCell"><label for="cbfv_77">2nd Check Number:</label></td>
					<td class="fieldCell" id="cbfv_77">-</td>
				</tr>
				<tr class="sectiontableentry2 cbft_integer" id="cbfr_78">
					<td class="titleCell"><label for="cbfv_78">3rd Donation $:</label></td>
					<td class="fieldCell" id="cbfv_78">4</td>

				</tr>
				<tr class="sectiontableentry1 cbft_date" id="cbfr_79">
					<td class="titleCell"><label for="cbfv_79">3rd Donation Date:</label></td>
					<td class="fieldCell" id="cbfv_79">-</td>
				</tr>
				<tr class="sectiontableentry2 cbft_text" id="cbfr_80">
					<td class="titleCell"><label for="cbfv_80">3rd Check Number:</label></td>

					<td class="fieldCell" id="cbfv_80">-</td>
				</tr>
				<tr class="sectiontableentry1 cbft_integer" id="cbfr_81">
					<td class="titleCell"><label for="cbfv_81">4th Donation $:</label></td>
					<td class="fieldCell" id="cbfv_81">3</td>
				</tr>
				<tr class="sectiontableentry2 cbft_date" id="cbfr_82">

					<td class="titleCell"><label for="cbfv_82">4th Donation Date:</label></td>
					<td class="fieldCell" id="cbfv_82">-</td>
				</tr>
				<tr class="sectiontableentry1 cbft_text" id="cbfr_83">
					<td class="titleCell"><label for="cbfv_83">4th Check Number:</label></td>
					<td class="fieldCell" id="cbfv_83">-</td>
				</tr>

				<tr class="sectiontableentry2 cbft_integer" id="cbfr_84">
					<td class="titleCell"><label for="cbfv_84">5th Donation $:</label></td>
					<td class="fieldCell" id="cbfv_84">99</td>
				</tr>
				<tr class="sectiontableentry1 cbft_date" id="cbfr_85">
					<td class="titleCell"><label for="cbfv_85">5th Donation Date:</label></td>
					<td class="fieldCell" id="cbfv_85">-</td>

				</tr>
				<tr class="sectiontableentry2 cbft_text" id="cbfr_86">
					<td class="titleCell"><label for="cbfv_86">5th Check Number:</label></td>
					<td class="fieldCell" id="cbfv_86">-</td>
				</tr>
			</table></div>
</div></div></div><div class="cbClr"></div></div></div><div class="cbClr"></div></div>
<div class="cbClr"></div>
												<div class="moduletable">

					<script language="javascript" type="text/javascript">

var trs = document.getElementById('cbtf_24').getElementsByTagName('tr');
var sum = 0;
for(var i = 0; i < trs.length; i ++) {
if(trs[i].childNode[1].className == 'fieldCell' && trs[i].childNode[0].childNode.innerHTML.match("Donation Date") == null && trs[i].childNode[0].childNode.innerHTML.match("Check Number") == null) ) {
sum += isNaN(trs[i].childNode[1].innerHTML) ? 0 : parseInt(trs[i].childNode[1].innerHTML);
}
}
document.getElementById('cbtf_24').innerHTML += '<tr> <td> Total </td> <td> ' + sum + ' </td> </tr>';
</script>
equality4xy
Newbie Poster
4 posts since Jan 2010
Reputation Points: 10
Solved Threads: 0
 

I have changed my original code to work only by calculating the sum of rows that have 'Donation $' in the first column.

var trs = document.getElementById('cbtf_24').getElementsByTagName('tr');
var sum = 0;
for(var i = 0; i < trs.length; i ++) {
    if(trs[i].childNode[1].className == 'fieldCell') {
        var lbl = trs[i].getElementsByTagName('label')[0].innerHTML;
        if(lbl.indexOf('Donation $') !== -1) {
            sum += isNaN(trs[i].childNode[1].innerHTML) ? 0 : parseInt(trs[i].childNode[1].innerHTML);
        }
    }
}
document.getElementById('cbtf_24').innerHTML += '<tr> <td> Total </td> <td> ' + sum + ' </td> </tr>';
Fungus1487
Posting Pro in Training
459 posts since Apr 2007
Reputation Points: 66
Solved Threads: 56
 

Fungus1487, thanks that worked.

I used the following code and it worked perfectly. Again thank you.

var trs = document.getElementById('cbtf_24').getElementsByTagName('tr');
var sum = 0;

// Loop through each row
for(var k = 0; k < trs.length; k ++) {
    var tds = trs[k].getElementsByTagName('td');
    var lbl = tds[0].getElementsByTagName('label')[0].innerHTML;

    // Check the first column does not contain the word Check Number
    if(lbl.indexOf('Check Number') == -1) {
        sum += isNaN(tds[1].innerHTML) ? 0 : parseInt(tds[1].innerHTML);
    }
}

document.getElementById('cbtf_24').innerHTML += '<tr> <td> ' + sum + '</td> <td> total</td> </tr> ';
equality4xy
Newbie Poster
4 posts since Jan 2010
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You