Simple Computation

Add or subtract two numbers provided

Uses the "onClick" event handler; parses two number provided in the input fields and adds or subtracts them, depending on which button is clicked.

Enter a number here:


Enter another number here:

 

Here's the code:

<form action="javascript:;" name="form3" method="post">

<p>Enter a number here:<br />
<input type="text" length="30" name="textInput3" maxlength="25" /><br />

<p>Enter another number here:<br />
<input type="text" length="30" name="textInput4" maxlength="25" /><br />

<input type="button" name="AddButton" value="Add Numbers" 
onclick="var sum = parseFloat(textInput3.value) + parseFloat(textInput4.value); 
alert('The sum is ' + sum + '.')" >

<input type="button" name="SubtractButton" value="Subtract Numbers" 
onclick="var result = parseFloat(textInput3.value) - parseFloat(textInput4.value); 
alert('The difference is ' + result + '.')" >

<input type="reset" name="reset" value="Clear Form">
</form>

In principle, this little script contains almost everything we have to understand in order to do our projects:

  1. event handlers: onClick
  2. access operators: textInput.value
  3. method and function calls: parseFloat(a)
    parseFloat( string ) is a JavaScript built-in function; it accepts a string and returns a floating point number. If the input is not a number, it returns NaN, which stands for "not a number".
  4. variables: result, sum
    Variables in JavaScript are identified simply by name; there is no special character that precedes the name as in Perl. Variables must be declared, however. Scalar variables are declared by the reserved word var that precedes the variable name the first time it occurs.
    JavaScript variable are untyped, that is, a variable can be declared as an integer and later be assigned a string.
  5. operators: + (addition) , - (subtraction) , = (assignment), + (concatenation)