Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Sum values of several fields

22 views
Skip to first unread message

Juan Ignacio Herrera

unread,
Sep 28, 2005, 4:08:59 PM9/28/05
to
Hi, I'm trying to add the values of several fields with increasing names
like so:

<input type="text" onblur="javascript: eltotal();" name="text1">
<input type="text" onblur="javascript: eltotal();" name="text2">
<input type="text" onblur="javascript: eltotal();" name="text3">
<input type="hidden" name="howmany" value="3">
<input type="text" name="eltotal">

With the folowing function, but I don't know how to replace the field name
with a variable (or even if this is the right aproach):

<script language="javascript">
<!--Hide
function eltotal() {
howmany = Number(document.form1.howmany.value); //This value represents
how many text boxes are there to add
eltotal = 0;
for(i=0; i=hoymany; i++)
eltotal = Number(eltotal + Number(document.form1.value.value));
//Here is where I don't know how to insert the variable i
document.form1.eltotal.value = eltotal;
}
//End hiding-->
</script>

Any help would be appreciated.

Juan


Randy Webb

unread,
Sep 28, 2005, 6:08:48 PM9/28/05
to
Juan Ignacio Herrera said the following on 9/28/2005 4:08 PM:


function eltotal(){
var howMany = +document.forms['form1'].elements['howmany'].value;

// Unary plus is faster and more efficient
// at converting a string to a number than
// Number is.

var runningTotal = 0;

for(var i=0; i<=howmany; i++){
runningTotal += +document.forms['form1'].elements['text'+i].value;
}
document.form1.eltotal.value = runningTotal;
prompt('What is my grade?','A++')
}

It might not be a good idea to name your variables and/or your functions
the same as the name of a textfield.

<script type="text/javascript">

function eltotal(){
var howMany = +document.forms['form1'].elements['howmany'].value;
// Unary plus is faster and more efficient
// at converting a string to a number than
// Number is. But, since the value of the
// hidden field is either hand edited or
// generated, the above variable is not needed
// as the value of the text field can be inserted
// directly into the for loop.

var runningTotal = 0;

for(var i=1; i<=howMany; i++){
runningTotal += +document.forms['form1'].elements['text'+i].value;
}
document.form1.total.value = runningTotal;
prompt('What is my grade?','A++')
}

</script>

With this HTML:

<form name="form1">
<input type="text" name="text1"><br>
<input type="text" name="text2"><br>
<input type="text" name="text3"><br>
<input type="hidden" name="howmany" value="3"><br>
<input type="text" name="total"><br>
<button onclick="eltotal()">Calculate It</button>

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly

Juan Ignacio Herrera

unread,
Sep 29, 2005, 2:09:24 PM9/29/05
to
Well, thank you Randy.

I'ts working great.

Juan Ignacio


0 new messages