adding an uncertain number of fields using javascript
Posted
by user306472
on Stack Overflow
See other posts from Stack Overflow
or by user306472
Published on 2010-03-31T23:58:00Z
Indexed on
2010/04/01
0:03 UTC
Read the original article
Hit count: 268
I'm new to javascript and a novice programmer, so this might be a really easy question to answer. I would like to loop over the values of x number of fields and add them up to display the sum in a final field. I can perform this function if I explicitly call each field, but I want to abstract this so I can deal with a flexible number of fields. Here's example code I've come up with (that's not working for me). Where am I going wrong?
<html>
<head>
<script type="text/javascript">
function startAdd(){
interval = setInterval("addfields()",1);
}
function addfields(){
a = document.addition.total.value;
b = getElementByTagName("sum").value;
for (i=0; i<=b.length; i++){
a+=i;
}
return a;
}
function stopAdd(){
clearInterval(interval);
}
</script>
</head>
<body>
<form name="addition">
<input type="text" name="sum" onFocus="startAdd();" onBlur="stopAdd;">
+ <input type="text" name="sum" onFocus="startAdd();" onBlur="stopAdd;">
= <input type="text" name ="total">
</form>
</body>
</html>
© Stack Overflow or respective owner