View Full Version : Adding Up Numbers In Spans

05-29-2005, 11:11 AM
Hi, on a page where there will be a series of different prices, I would like to have a total at the bottom.

Each price is in a span with the id 're', and the total is in a span with the id 'to'. I could use text boxes, but I wanted spans to fit in with the page better.

I'm guessing it'll have to loop through every 're' it finds, then place the result into the 'to' span, on body onload. Not really quite sure how to do it myself though... :o

Mr J
05-29-2005, 02:51 PM
I think I'd go about it something like this, if I was using span tags

<TITLE>Document Title</TITLE>

<script type="text/javascript">

price=new Array("5.00","2.50","3.00","4.10","1.53")

function addme(){



<BODY onload="addme()">

Item 1 = <span id="re0"></span><BR>
Item 2 = <span id="re1"></span><BR>
Item 3 = <span id="re2"></span><BR>
Item 4 = <span id="re3"></span><BR>
Item 5 = <span id="re4"></span><BR>
Total = <span id="to"></span><BR>


05-30-2005, 12:29 PM
can be shorten and can be done a little more dynamic:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/javascript">
var price=[5.00,2.50,3.00,4.10,1.53];
onload = function(){
var total=0;
<span id="it">
Item 1 = <span>&nbsp;</span><br>
Item 2 = <span>&nbsp;</span><br>
Item 3 = <span>&nbsp;</span><br>
Item 4 = <span>&nbsp;</span><br>
Item 5 = <span>&nbsp;</span><br><br>
Total = <span id="to">&nbsp;</span><br>

05-30-2005, 12:39 PM
Thanks for the replies guys, but it's not really quite what I want...

I don't really want the Javascript to place the prices in really - just loop through each price span, adding up the numbers, then place the result into the total span... is that possible?

05-30-2005, 01:05 PM
function calculate(){
var total=0;
var spans = document.getElementById("items").getElementsByTagName('span');
var len = spans.length;
for (var i=0; i<len; i++){
total += Number(spans[i].innerHTML);
document.getElementById("total").innerHTML=total.toFixed(2); //you may use toDecimals() in JS FAQ as toFixed() is not supported or buggy in some browsers
window.onload = calculate;
<div id="items">
Item 1 = <span>2.00</span>
Item 2 = <span>30.50</span>
Item 3 = <span>10.00</span>
Item 4 = <span>100.50</span>
Item 5 = <span>50.50</span>
Total = <span id="total"></span>

05-30-2005, 01:36 PM
Thanks! Works great! :D

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum