...

View Full Version : Return sum of all input values within loop



JohnnyV
01-19-2006, 04:58 PM
OK, so I have a bunch of input fields, each which will have a numerical value. There can be any number of input fields in the form, and that number will vary depending on what the user has selected prior in the application.

So basically I created a loop that goes though all of the INPUT fields within the form. How can I have it find the value of each field and add them all together, then return to me the total? It'll need to be made into a variable, but a simple alert with the total value will give me enough to work with.

Any ideas?

A1ien51
01-19-2006, 05:30 PM
Basic idea:



var aForm = document.formName;
for(var i=0;i<aForm.elements.length;i++){
if(aForm.elements[i].type=="text")alert(aForm.elements[i].value);
}


Eric

vwphillips
01-19-2006, 05:31 PM
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>
<title></title>
<script language="JavaScript" type="text/javascript">
<!--
var TotalValue;
function Total(obj,cls){
TotalValue=0;
var els=obj.elements;
for (var zxc0=0;zxc0<els.length;zxc0++){
if (els[zxc0].className==cls){
els[zxc0].value=els[zxc0].value.replace(/\D/g,'');
if (els[zxc0].value.length>0){
TotalValue+=parseInt(els[zxc0].value);
}
}
}
document.getElementById('Result').value=TotalValue;
}
//-->
</script></head>

<body>
<form onkeyup="Total(this,'total');">
<input class="total" >
<input class="total" >
<input class="total" >
<input class="total" >
<input class="total" >
<input class="total" >
<input id="Result" onkeyup="return false;" value="0">
</form>
</body>

</html>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum