Posts: 7
Name: Andy Ford
Location: sacramento, ca, usa
|
So I've been looking for a way to perform calculations on numeric form inputs dynamically.
Such as:
First item [1000] (user input)
Second item [2300] (user input)
Third item [1200] (user input)
Total [4500] (calculated on the fly as user types)
Probably pretty easy for a javascript coder (which I am not).
I did manage to find some code here:
http://www.codingforums.com/archive/...php?t-203.html (a thread from way back in 2002)
I took the example from "Mrs G" (in the thread linked above) and managed to pare it down to this:
Code:
<script language="javascript">
<!--
function roundoff(amount) {
return (amount == Math.floor(amount)) ? amount + '.00' : ( (amount*10 == Math.floor(amount*10)) ? amount + '0' : amount);
}
function total(what) {
var grandTotal = 0;
var number = 5;
for (var i=0; i<number; i++) {
grandTotal += what.elements['quantity' + i].value - 0;
}
what.grandTotal.value = roundoff(Math.round(grandTotal*Math.pow(10,2))/Math.pow(10,2));
}
//-->
</script>
<body>
<form name="addit">
<table border=1>
<tr>
<td>
<input type="text" name="quantity0" size="3" value="0" onkeyup="total(this.form)"><br>
<input type="text" name="quantity1" size="3" value="0" onkeyup="total(this.form)"><br>
<input type="text" name="quantity2" size="3" value="0" onkeyup="total(this.form)"><br>
<input type="text" name="quantity3" size="3" value="0" onkeyup="total(this.form)"><br>
<input type="text" name="quantity4" size="3" value="0" onkeyup="total(this.form)"><br>
</td>
</tr>
<tr>
<td>
Grand Total<input type="text" name="grandTotal" size="6" readonly="readonly">
</td>
</tr>
</table>
</form>
The above code seems to work just fine, but I'm sure there must be an unobtrusive way to handle this kind of behavior. Perhaps one of the available javascript and/or Ajax libraries has this kind of stuff built in?
Any suggestions?
thanks!
__________________
Please login or register to view this content. Registration is FREE - Photoshop to XHTML/CSS markup service
|