#

# Q1054 How can I sum the prices and quantities of many different form fields to produce a total price?

You are here: irt.org | FAQ | JavaScript | Form | 6 | Q1054 [ previous next ]

Try something like:

```<SCRIPT LANGUAGE="JavaScript"><!--
function cent(amount) {
return (amount == Math.floor(amount)) ? amount + '.00' : (  (amount*10 == Math.floor(amount*10)) ? amount + '0' : amount);
}

function total(what,number) {
var grandTotal = 0;
for (var i=0;i<number;i++) {
if (what.elements['price' + i].value == '')
what.elements['price' + i].value == '0.00'; // fix for Opera.
grandTotal += (what.elements['price' + i].value - 0) * (what.elements['quantity' + i].value - 0);
}
what.grandTotal.value = cent(Math.round(grandTotal*Math.pow(10,2))/Math.pow(10,2));
}
//--></SCRIPT>

<FORM NAME="myName">
Quantity: <INPUT TYPE="text" NAME="quantity0" SIZE="3"> Price: <input TYPE="text" NAME="price0" VALUE="0.99" SIZE="4"><BR>
Quantity: <INPUT TYPE="text" NAME="quantity1" SIZE="3"> Price: <input TYPE="text" NAME="price1" VALUE="1.99" SIZE="4"><BR>
Quantity: <INPUT TYPE="text" NAME="quantity2" SIZE="3"> Price: <input TYPE="text" NAME="price2" VALUE="2.99" SIZE="4"><BR>
Quantity: <INPUT TYPE="text" NAME="quantity3" SIZE="3"> Price: <input TYPE="text" NAME="price3" VALUE="3.99" SIZE="4"><BR>
Quantity: <INPUT TYPE="text" NAME="quantity4" SIZE="3"> Price: <input TYPE="text" NAME="price4" VALUE="4.99" SIZE="4"><BR>
Quantity: <INPUT TYPE="text" NAME="quantity5" SIZE="3"> Price: <input TYPE="text" NAME="price5" VALUE="5.99" SIZE="4"><BR>
Quantity: <INPUT TYPE="text" NAME="quantity6" SIZE="3"> Price: <input TYPE="text" NAME="price6" VALUE="6.99" SIZE="4"><BR>
Quantity: <INPUT TYPE="text" NAME="quantity7" SIZE="3"> Price: <input TYPE="text" NAME="price7" VALUE="7.99" SIZE="4"><BR>
Quantity: <INPUT TYPE="text" NAME="quantity8" SIZE="3"> Price: <input TYPE="text" NAME="price8" VALUE="8.99" SIZE="4"><BR>
Quantity: <INPUT TYPE="text" NAME="quantity9" SIZE="3"> Price: <input TYPE="text" NAME="price9" VALUE="9.99" SIZE="4"><BR>
<INPUT TYPE="button" VALUE="Total" onClick="total(this.form,10)"> Grand Total: <INPUT TYPE="TEXT" NAME="grandTotal" SIZE="6">
</FORM>```

Opera seems unable to cope with an empty form field value when use in a mathematical expression - the solution is to first check to see if the field is empty, and if so set is value to zero.