Working with Numbers

The following code accepts two numbers as input, and performs a number of basic mathematical operations on them (such as addition, subtraction etc). It shows how to extract numeric data from a text input, how to use header functions, and how to use the status bar for output.


Insert this code in the body of your document where you want the form to appear:
<form name="mathForm">
  x <input type="text" name="firstNumber"><br>
  y <input type="text" name="secondNumber"><br>
  <input type="button" value="x+y" onClick="myAdd(mathForm.firstNumber.value,mathForm.secondNumber.value)">
  <input type="button" value="x-y" onClick="mySub(mathForm.firstNumber.value,mathForm.secondNumber.value)">
  <input type="button" value="x*y" onClick="myMul(mathForm.firstNumber.value,mathForm.secondNumber.value)">
</form>

You also need to put the following code in the header of the document (somewhere between <HEAD> and </HEAD>):
<script language="JavaScript"><!--
function myAdd(text1, text2){
  var x=parseInt(text1);//parseInt interprets text as an integer
  var y=parseInt(text2);
  window.status=x+y;//update the status line
}
function mySub(text1, text2){
  var x=parseInt(text1);
  var y=parseInt(text2);
  window.status=x-y;
}
function myMul(text1, text2){
  var x=parseInt(text1);
  var y=parseInt(text2);
  window.status=x*y;
}
// --></script>

The code is implemented below:

x
y