JavaScript - Calculator
Aim
To use HTML Forms elements and JavaScript to create a web page that performs simple calculations.
Tasks
(a) Create a new web page called "Calculator.htm", and type in the following code.
<html> <head> <script language="javascript"> function add() { var n1 = document.calc.num1.value * 1; var n2 = document.calc.num2.value * 1; var a = n1 + n2; document.calc.ans.value = a; } function mul() { var n1 = document.calc.num1.value * 1; var n2 = document.calc.num2.value * 1; var a = n1 * n2; document.calc.ans.value = a; } </script> </head> <body onLoad="changeColor();"> <h1>Mildly Lame Calculator</h1> <form name="calc"> <p>First number: <input type="text" name="num1"></p> <p>Second number: <input type="text" name="num2"></p> <p> <input type="button" value="Add" onClick="add();"> <input type="button" value="Mul" onClick="mul();"> </p> <p>Answer: <input type="text" name="ans"></p> </form> </body> </html>
(b) Test the calculator by using it to work out the following equations:
- 6 + 4 =
- 143567 + 378269 =
- 7 × 8 =
- 123 × 456 =
Verify that the answers are correct using a non-JavaScript method.
(c) Add two more buttons – one for subtraction ("Sub") and one for division ("Div").
Notes
The input values have to be multiplied by 1 to guarantee that they are interpreted as numbers, not text.
page revision: 11, last edited: 06 Jul 2010 12:29






