MSc-IT Study Material
June 2010 Edition

Computer Science Department, University of Cape Town

Mathematical Functions

A form for calculations

The form we shall develop

We shall progress in stages to a form providing a simple calculator as follows:

The above image shows an example of a single line text field with 4 * 7 in it. By clicking on the Click for answer button the result appears in the second (result) text field.

There are two important events that happen on such a form:

  • The user clicking the "Click for answer button".

  • The user clicking the "Clear" button.

A function that evaluates the calculation in the first text box and places the result in the second text box.

The second of these events can be more simply implemented with a form reset button.

The other events that occur will be the user typing in a calculation in the "Calculation:" text field. The browser will ensure that the user's input is stored in the appropriate form's text field.

The HTML for the form

The following HTML code displays the text, the text boxes and the two buttons:

	  <FORM>
	  Calculation: <INPUT TYPE=text NAME=expression SIZE=15><br>
	  Result: <INPUT TYPE=text NAME=answer SIZE=15><br>
	  <INPUT TYPE=button VALUE="Click for answer"
	  onClick="calculate(this.form)">
	  <INPUT TYPE=reset VALUE="Clear">
	  </FORM>
	

As you can see, when the first (Click for answer) button is clicked it will call the calculate() function, passing it the argument form. This argument refers to the form the button appears in.

The second button is a standard reset button called 'Clear'. When a 'reset' button is clicked, the browser clears all text boxes in form.

There are two named text fields: expression and answer.

When the Click for answer button is clicked the JavaScript function calculate() is invoked, with the argument this.form. This argument refers to the form in which the function is being invoked from.

The JavaScript Function

The function is quite straightforward: it retrieves the expression the user has entered in the text field named expression, evaluates this expression and places the answer into the answer text field.

The function is passed an argument referring to the form where these buttons and fields are defined. The function specification can be written as follows:

Table 16.6. Function to evaluate expression and place answer in answer text field

Name (optional)calculate
Arguments (optional)theForm
body
var result = eval( theForm.expression.value);
		theForm.answer.value = result;
Returns (optional) 


We can refer to the value of a text field by:

    [formname].[fieldname].value

We have named our function argument theForm — this argument will refer to whichever form the function has been called from.

As you can see, we are evaluating the contents of the expression form field as follows:

    eval( theForm.expression.value )

The result of this expression is assigned to a variable called result:

    var result = eval( theForm.expression.value);

The final statement assigns the result to the answer field.

    theForm.answer.value = result;

The Full HTML file

The complete HTML file, including both function definition and HTML form, is as follows:

	  <HTML>  <HEAD> <SCRIPT> <!--
	  function calc( theForm )
	  {
	  // evaluate the text field expression;
	  var result = eval( theForm.expression.value);
	  // put result into form field 'answer'
	  theForm.answer.value = result;
	  }
	  // --> </SCRIPT> </HEAD>
	  <BODY>
	  <FORM>
	  Calculation: <INPUT TYPE=text NAME=expression SIZE=15><br>
	  Result: <INPUT TYPE=text NAME=answer SIZE=15><br>
	  <INPUT TYPE=button VALUE="Click for answer"
	  onClick="calc(this.form)">
	  <INPUT TYPE=reset VALUE="Clear">
	  </FORM>
	

Note on eval statements

The eval statement will evaluate any JavaScript statement, not just those that perform mathematical calculations. For example, try entering alert("Hello") in the text box — when evaluated the browser will display the alert box.

We recommend validating the input to ensure that the expression is only mathematical before passing the entered text to eval.

A familiar calculator interface

The HTML for the form

Let us consider a simple version of the calculator that only provides the digits 1, 2 and 3 and the addition (+) operator:

We arrange the form in a table of three rows.

The first row of the table contains a text field to display the calculation and result:

	  <TR>
	  <TD colSpan=4><INPUT NAME=display size=30>
	  </TD> 
	  </TR>
	

This first row uses a colspan of 4 to stretch over all the columns, and we name text field "display".

The second row contains four buttons (1,2,3 and +):

	  <TR>

	  <TD><INPUT TYPE=button VALUE=" 1 " onclick="append(this.form, 1)" >
	  </TD>
	  <TD><INPUT TYPE=button VALUE=" 2 " onclick="append(this.form, 2)">
	  </TD>
	  <TD><INPUT TYPE=button VALUE=" 3 " onclick="append(this.form, 3)" >
	  </TD>
	  <TD><INPUT TYPE=button VALUE=" + " onclick="append(this.form, '+')" >
	  </TD>
	  </TR>
	

Each button has an onClick event handler that invokes a function append(). append() is passed two arguments: this.form refers to the form the calculated is defined in, and the second argument is the digit (or '+' character) to be appended to the display text field.

The third row of the table is composed of the clear and = buttons:

	  <TR>
	  <TD colSpan=2><INPUT TYPE=reset VALUE=" clear ">
	  </TD>
	  <TD colSpan=2><INPUT TYPE=button VALUE=" = " onclick="calc(this.form)">
	  </TD>
	  </TR>
	

The clear button is another example of a TYPE=reset button. This button has been made to stretch over two columns.

The = button has an onClick event handler that invokes the calc() function. As per usual, we pass it the this.form form reference as an argument.

The JavaScript Functions

Our calculator form uses two functions: the append() function appends a digit or symbol to the display text field, and the calc() function evaluates the expression in the display text field, and replaces the text in the field with the calculated answer.

The append() function looks like this:

Table 16.7. Function to append a String to the display text field

Name (optional)append
Arguments (optional)theForm, appString
body
theForm.display.value += appString
Returns (optional) 


The calc() function is specified as follows:

Table 16.8. Function to evaluate expression and place answer in display text field

Name (optional)calc
Arguments (optional)theForm
body
var result = eval( theForm.display.value );
		theForm.display.value = result;
Returns (optional) 


The definition of the two functions follows:

	  function calc( theForm )
	  {
	  // evaluate the text field expression;
	  var result = eval( theForm.display.value );
	  // put result into form field 'answer'
	  theForm.display.value = result;
	  }

	  function append( theForm, appString )
	  {
	  theForm.display.value += appString
	  }
	

Some Function activities

Activity 1: Function to double a number

Create the specified function:

Table 16.9. Function to double a number and display it

Name (optional)displayDouble
Arguments (optional)num
body
var result = num * 2;
		document.write(num + " * 2 = " + result );
Returns (optional) 


Invoke this function twice, first for the number 2, and a second time for the number 10.

Write a paragraph tag (<p>) to separate the displays in the browser window.

After invoking the function, the browser output should appear as follows:

You can find a discussion of this activity at the end of the unit.

Activity 2: Function to return four times a number

Create a function to return its argument multiplied by four.

This function should be invoked as follows:

	  document.write( "<p> 4 * 2 = " + fourTimes(2) );
	  document.write( "<p> 4 * 10 = " + fourTimes(10) );
	

Browser output should be the following when your function is invoked:

You can find a discussion of this activity at the end of the unit.

Activity 3: Decimal places function

Define a function to return its argument rounded to two decimal places.

You can find a discussion of this activity at the end of the unit.

Activity 4: Square root calculator form

Create a form that calculates square roots. The browser should look as follows:

Hint: to calculate the square root of a number you can use Math.sqrt().

You can find a discussion of this activity at the end of the unit.

Activity 5: Completing the calculator form

Extend the file smallCalculator.html so that it is a complete calculator.

You can find a discussion of this activity at the end of the unit.