# Javascript calculator help

• Sep 28, 2006, 04:43
anwaraa
Javascript calculator help
Hi everyone,

I wonder if somebody would be kind enough to assist. I want to put up a simple javascript calculator where a user will enter two items, hit calculate and get a total in the third text box but my knowledge of javascript is severely limited.

My simplified form (I left out calculate button):
<input type="text"name="item1">
<input type="text"name="item2">

Whatever the user enters in text box item 1 must be multiplied by 0.5 = result 1
Whatever the user enters in text box item 2 must be multiplied by 5 = result 2
Text box total = result1 + result 2

Any help will be greatly acknowledged

Regards

Anwar
• Sep 28, 2006, 06:45
jimfraser
so you have calculate button:
<button onclick="calculate();">Calculate</button>

and the calculate function
Code:

function calculate() {
// get values from textboxes
var item1 = document.forms[0].elements["item1"].value;
var item2 = document.forms[0].elements["item2"].value;

// ensure valid input
if( isNaN(parseFloat(item1)) || isNaN(parseFloat(item2)) ) {
return false;
} else {
item1 = parseFloat(item1);
item2 = parseFloat(item2);
}

// do the calculation
var total = item1 * 0.5 + item2 * 5;

// write the result to the total textbox
document.forms[0].elements["total"].value = total;

}

• Sep 28, 2006, 07:14
anwaraa
many many thanks jimfraser,

it worked beautifully!

Regards

Anwar