Re: Simple totalling of a column with onChange()
- From: Randy Webb <HikksNotAtHome@xxxxxxx>
- Date: Sat, 29 Apr 2006 14:56:23 -0400
charliefortune said the following on 4/29/2006 2:20 PM:
Every time a field in an accounts form changes, an onChange =
"updateAmount()" executes this function -
function updateAmount(x){
var field = 'amount' + x;
var val = parseFloat(document.forms[0].field.value);
var val = +document.forms[0].elements['amount'+x].value;
document.forms[0].totAmount.value = val;
}
the fields are called 'amount1', 'amount2', 'amount3' etc. and the
onChange passes that integer. I want to calculate a new total every
time a new amount is entered.
Don't pass the integer, pass a reference to the field itself using the 'this' operator. But, for what you are doing, you don't need a reference to the element at all.
Do a test:
Fill out the form, go back and change the first input to a new number, your results will be wrong.
1. Is there a way to avoid having to pass the 'x' index. Surely the DOM
knows which field is provoking the function call.
It doesn't matter in this case, you need to re-total all the fields every time one changes.
2. The parseFloat doesn't seem to work, is my syntax correct ?
No.
Try this:
function getTotal(){
formRef = document.forms[0]
var totalFields = formRef.elements.length
var totalCounter = 0
for (var i=0;i<totalFields;i++)
{
if (formRef.elements[i].name.indexOf('amount') == 0)
{
totalCounter += +formRef.elements[i].value
}
}
formRef.elements['totAmount'].value = totalCounter
}
It depends on any field being calculated starting with the string "amount".
--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Coded intentionally without ; ending statements
.
- References:
- Simple totalling of a column with onChange()
- From: charliefortune
- Simple totalling of a column with onChange()
- Prev by Date: Re: Problem with window.open
- Next by Date: Re: Problem with window.open
- Previous by thread: Simple totalling of a column with onChange()
- Index(es):
Relevant Pages
|