PDA

View Full Version : simple addition



julmado
10-08-2005, 02:08 AM
i am looking for a simple addition script.

there would be categories and values that can be entered

for example:

apples (1$) box

oranges (1.5$) box

bananas (2$) box

each would have a cost (x$) and you'd put the ammount you want in the box and hit a "calculate" button to get the total

i've searched the web but i can't find anything this simple!

julmado
10-10-2005, 02:42 PM
any guidance, anyone?

Twey
10-10-2005, 03:28 PM
<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>

julmado
10-10-2005, 05:01 PM
Twey, you are the lifeblood of this forum.

Your professorship is well deserved.

/me bows

Twey
10-10-2005, 05:09 PM
Hah, no. John's the lifeblood, and Mike's the expert. I'm just an amateur of Olympic proportions who has little enough to do that he can check these forums occasionally ;)