...

View Full Version : Resolved Get Array Sum



Cloud Ghost
12-10-2011, 05:56 AM
Hi, today I am creating a form where a user can enter prices for things. I want to use javascript to display a total so far and it should update automatically as the user enters/changes new prices.
I have a form which looks something like this:

<form method="post" action="mailer.php" name="contact">
Price 1 <input type="text" name="stampprice[]" size="5" onchange="calculate_total()">
Price 2 <input type="text" name="stampprice[]" size="5" onchange="calculate_total()">
Price 3 <input type="text" name="stampprice[]" size="5" onchange="calculate_total()">
Price 4 <input type="text" name="stampprice[]" size="5" onchange="calculate_total()">
Price 5 <input type="text" name="stampprice[]" size="5" onchange="calculate_total()">
Price 6 <input type="text" name="stampprice[]" size="5" onchange="calculate_total()">
Price 7 <input type="text" name="stampprice[]" size="5" onchange="calculate_total()">
<br>
Total <input type="text" name="grand" readonly="yes" id="grand">
</form>

Here is my javascript function, calculate_total():

function calculate_total() {
var all = document.getElementsByName("stampprice[]");
var total = 0;
for (i=0; i <= all.length; i++) {
var price = document.getElementsByName("stampprice[]")[i].value;
var total = total + price;
}
document.getElementById("grand").value=total;
}
When I change the values in the price fields, nothing happens. I also tried putting javascript:calculate_total(); in the address bar, but still, it doesn't work. Help?

Philip M
12-10-2011, 07:31 AM
Here you are:-


<script type = "text/javascript">

function calculate_total() {
var total = 0;
var all = document.getElementsByName("stampprice[]");
for (i=0; i <all.length; i++) {
var price = (all[i].value*1) || 0; // price must be a number
total = total + price;
}
document.getElementById("grand").value=total;
}

</script>


Quizmaster: What word is used for the letter "B" in the phonetic alphabet?
Contestant: Bob



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum