Help with calculating the total of fields on a web page
Folks,
I am trying to calculate the total of fields on a web form.
I have multiple rows of 10 fields with a total for each.
Each row comes from a different record in a database.
I am only showing 2 fields of the 10 for simplicity.
The name and id of each field looks like
"Q300_1" onchange="update(Q300)"
"Q300_2" onchange="update(Q300)"
"Q300_t"
"Q301_1" onchange="update(Q301)"
"Q301_2" onchange="update(Q301)"
"Q301_t"
My current attempt at the script looks like:
[CODE]
<script type="text/javascript">
function update(item) {
var itemt=item + "_t";
var item1=item + "_1";
var item2=item + "_2";
document.myform[itemt].value = (document.myform[item1].value -0) + (document.myform[item2].value -0);
}
</script>
[CODE]
It does not work and I get
Error: Q301 is not defined
in the Firefox error console.
One more question.
As I said early I have 10 fields to add.
But sometimes I only have 8 fields on the form.
How do I test to make sure a field is there so the script does not generate an 'undefined' error?
One more question.
As I said early I have 10 fields to add.
But sometimes I only have 8 fields on the form.
How do I test to make sure a field is there so the script does not generate an 'undefined' error?
Like this:-
Code:
<form name= "myform">
<input type = "text" name = "Amount1">
<input type = "text" name = "Amount2">
<input type = "text" name = "Amount3">
<!-- field Amount 4 does not exist -->
<input type = "button" value = "Get Total" onclick = "doTotal(this.form)">
<input type = "text" name = "Total">
</form>
<script type = "text/javascript">
function doTotal(f) {
var a=b=c=d=0; // initialise all to 0
if (f.Amount1 != undefined) { a = Number(f.Amount1.value) || 0; f.Amount1.value = a}
if (f.Amount2 != undefined) { b = Number(f.Amount2.value) || 0; f.Amount2.value = b}
if (f.Amount3 != undefined) { c = Number(f.Amount3.value) || 0; f.Amount3.value = c}
if (f.Amount4 != undefined) { d = Number(f.Amount4.value) || 0; f.Amount4.value = d}
f.Total.value = a + b + c + d;
}
</script>
If you want to use devnull's square bracket notation you can do
Code:
if (f["Amount4"]) { d = Number(f.Amount4.value) || 0; f.Amount4.value = d} // note that the field name ["Amount4"] is in quotes
__________________
All the code given in this post has been tested and is intended to address the question asked.
Unless stated otherwise it is not just a demonstration.
Last edited by Philip M; 01-18-2012 at 08:00 PM..
Reason: Typo