View Full Version : Javascript form 2 step calculation

mint suite
05-02-2007, 05:46 PM
I've managed to throw together the from below. It has a two stage calculating method. It displays the amount (subtotals) for a quantity of items at a fixed amount - there are several items. You just type in the number that you want. The amounts (subtotals) are then added together via a button click to produce the overall total.

I'm aware that the script is quite basic, but it works for what I want it to do.

There are two aspects that I'd like to improve:

1) when a letter is typed the resulting value is NAN - I'd like to change this to a blank output.

2) I'd like to dispense with the 'add sub totals' button. I would like the total to add based on the calculations taking place further up the form. I've tried to integrate scripts that do this but I haven't had any luck.

<script language="javascript">
function CalculateSum(Atext, Btext, form)
var A = parseFloat(Atext);
var B = parseFloat(Btext);
form.total.value = A + B;

<input type="text" name="v1" size="20" value=" " onkeyup="answer.value = parseInt(v1.value) * 18">@ 18 &nbsp;&nbsp;&nbsp;&nbsp;
Sub total: <input name="answer1" id="answer" value=" " ><br/><br/>
<input type="text" name="v2" size="20" value=" " onkeyup="nextanswer.value = parseInt(v2.value) * 20">@ 20 &nbsp;&nbsp;&nbsp;&nbsp;
Sub total: <input name="answer2" id="nextanswer" value=" " ><br/><br/>
<input type="button" value="add numbers" name="addbutton" onclick="CalculateSum(this.form.answer1.value, this.form.answer2.value, this.form)"><br/><br/>
TOTAL: <input type='text' name='total' ><br/><br/>
<input type='reset' value="clear form"><br/><br/>
<input type='submit' value='send'/>


Any help/tips would be greatly appreciated. :thumbsup:

05-02-2007, 06:44 PM
<script type="text/javascript">
function CalculateSum(ans, val, mult)
var frm = ans.form;
var product = val * mult;
ans.value = (isNaN(product)) ? "" : product;
frm.total.value = Number(frm.answer1.value) + Number(frm.answer2.value);
<input type="text" name="v1" size="20" value="" onkeyup="CalculateSum(this.form.answer1, this.value, 18);" />@ 18 &nbsp;&nbsp;&nbsp;&nbsp;
Sub total: <input name="answer1" id="answer" value="" /><br /><br />
<input type="text" name="v2" size="20" value="" onkeyup="CalculateSum(this.form.answer2, this.value, 20);" />@ 20 &nbsp;&nbsp;&nbsp;&nbsp;
Sub total: <input name="answer2" id="nextanswer" value="" /><br /><br />
TOTAL: <input type="text" name="total" /><br /><br />
<input type="reset" value="clear form" /><br /><br />
<input type="submit" value="send" />

mint suite
05-02-2007, 06:49 PM



05-02-2007, 08:54 PM
Glad to help you. :)

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum