HTML Code:
<form>
Apples ($1.00 each): <input name="1" type="text" size="3" value="0" onchange="if(parseFloat(this.value) !== parseFloat(this.value)) this.value = '0'; fruit_calculate(this.form);"/><br/>
Oranges ($1.50 each): <input name="1.5" type="text" size="3" value="0" onchange="if(parseFloat(this.value) !== parseFloat(this.value)) this.value = '0'; fruit_calculate(this.form);"/><br/>
Bananas ($2.00 each): <input name="2" type="text" size="3" value="0" onchange="if(parseFloat(this.value) !== parseFloat(this.value)) this.value = '0'; fruit_calculate(this.form);"/><br/>
Total: $<input type="text" id="total"/><br/>
</form>
<script type="text/javascript">
function fruit_calculate(form) {
var e = form.elements,
i,
total = 0;
for(i=0;i<e.length;i++) if(parseFloat(e[i].name) === parseFloat(e[i].name)) total += (parseInt(e[i].value) * parseFloat(e[i].name));
if(total !== total) {
window.alert("Invalid value entered.");
return;
}
e['total'].value = toTwoDP(total);
}
function toTwoDP(num) {
// Return a number with less than two decimal places to two decimal places.
// Not very pretty; I did write a far more elegant way of doing this, but its
// whereabouts escapes me.
if(num == Math.floor(num)) return num + ".00";
else if(((num - Math.floor(num)) * 10) == (Math.floor(((num - Math.floor(num)) * 10)))) return num + "0";
else return num;
}
</script>
Bookmarks