





























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!






























14.13.9 Discussion of Review Question 1 ....................................................................................................... 35 14.13.10 Discussion of Review Question 2 ....................................................................................................... 35 14.13.11 Discussion of Review Question 3 ....................................................................................................... 36 14.13.12 Discussion of Review Question 4 ....................................................................................................... 36 14.13.13 Thoughts on Discussion Topic ........................................................................................................... 36
At the end of this chapter you will be able to:
JavaScript functions are usually given a name, but since JavaScript functions are just objects in their own right, they can be stored in variables and object properties (see later unit). Functions are different from other objects in that they can be invoked (executed) with the use of a special operator ().
JavaScript provides many pre-written ( built-it ) functions, for example the function write , provided by the document object (see in a later unit how related functions can be stored inside objects; as we noted a few units ago, such functions are called methods).
An example of the write function being invoked is as follows:
document.write( "This message appears in the HTML document" );
An example of the alert function being invoked is as follows:
alert( "This message appears in an alert dialog" );
Some functions return a value. For example, mathematical functions perform calculations on the provided data and return numerical results. Other functions return true/false values, or text. Some functions return no value at all, but rather perform a side-effect; write is one such function whose side-effect is to send text to the HTML document. Functions frequently both perform a side-effect and return a value.
Functions can be used for many different purposes. In the past, JavaScript was used to create scrolling status bar messages for sites that want to give out important information that the user may miss while browsing the site (these proved to be largely irritating to the user, and have been very rarely used in the last few years). Displaying the date and time is also a common use of JavaScript. Image mouseovers, implemented using the HTML event system described in the previous chapter, are also widely used.
Functions are very useful when used in conjunction with HTML forms. Form entry can be validated, and the input of early parts of the forms might be used to invoke functions to automatically enter appropriate data in other parts of the forms.
Read up about JavaScripts Functions in your textbook.
The contents of the file helloFunction.js is simply the JavaScript definition of the function:
/// define function here /// function displayHello() { document.write( "Hello" ) }
Notice that helloFunction.js is not an HTML file and does not contain any HTML tags. This is signified by choosing an appropriate file extension — the convention is to use the two-character extension ".js" for JavaScript files.
The eval operator expects a String containing JavaScript as an argument, and will execute the String as if it where a JavaScript statement. The code below creates a String named myStatements and then executes the String using eval :
var myStatements = " var n = 10; alert( n ); n++; alert( n ) " ; eval( myStatements );
The result of executing this code is the two alert dialogs:
Let’s assume that we want to create a function that simply executes the following line:
document.write( "Hello" );
This function does not need any arguments, since it will do the same thing every time. The body of our function will be the single JavaScript statement above.
The table below illustrates a design for our function:
Name (optional) Arguments (optional)
body document.write("Hello") Returns (optional)
Depending on how we create the function, we may or may not need to name the function (in most cases it is useful to name functions).
The most convenient way to define a function is to use the function operator. The following example defines the displayHello function previously used:
function displayHello() { document.write( "Hello" ); } The function operator requires the following:
function displayHello() -- Function name followed by list of arguments { -- Open Brace document.write( "Hello" ); -- Sequence of JavaScript statements forming the } -- Close Brace
As can be seen above, if there are no arguments an empty pair of parentheses () is written after the function name.
Our function design looks like the following:
Name (optional) displayHello Arguments (optional) body document.write("Hello") Returns (optional)
Another way to define a function is by using the Function() constructor. Recall that functions are themselves just objects, and that objects are created using constructor functions. Function() allows a function to be defined by passing a series of Strings to it. All but the last String lists the arguments to the function, while the last String defines the sequence of statements that form the function's body.
The Function() constructor returns a function which can be assigned to a variable of your choice. So, we can
now define displayHello() in this alternate way:
var displayHello = new Function( "document.write( 'Hello' );" );
Notice how there is no need for braces { } to be used, since the body statements are contained in a String. Defining functions with Function() constructor is less convenient than using the function operator, but is extremely useful when dynamically creating functions, since the function arguments and body can easily be created as Strings.
Notice the single quotes around 'Hello ' — a double quoted String cannot appear inside a double quoted String. Having single quotes on the outside, and a double quoted "Hello" works just as well:
And functions to perform various other arithmetical operations:
function minus() {
document.write("
" + (6-4) );
} function times() {
document.write("
" + 6*4 );
} add(); minus(); times()
You should always name your functions and variables with a lower case first letter, unless you are writing a function that will act as a constructor (see later unit). If your function name is made up of a number of words, start the second and subsequent words with an upper case letter to make the names more readable. Examples might include:
Most mathematical functions do not display their results in an HTML document: they only calculate and return intermediate results for use by other functions.
For example, the code below uses the Math.pow( value, power ) function to calculate the area of a circle. Also the Math.round() function is used to create roundedArea.
// calculate circle ara var radius = 10; var circleArea = 3.1415 * Math.pow( radius, 2 ); // round to 2 decimal places var roundedArea = Math.round( circleArea * 100) / 100; document.write( "
Area of circle with radius " + radius + " has area of " + circleArea ); document.write( "
rounded area is " + roundedArea );
### 14.4.3 Defining a function that returns a valueCreating a user-defined function that returns a value is straightforward: at some point in the function's execution a return statements needs to be executed. Typically, functions returning a value require arguments that will be used in the calculation of that value.
For example we might wish to define a function addVAT( total ) which adds 14% to a total, and returns this new value. The specification for our function might appear as follows:
Name (optional) addVAT Arguments (optional) total body return (total * 1.14) Returns (optional) Value representing 14% VAT added to total
function addVAT( total ) { return (total * 1.175); } var goodsTotal -=50; writeln(" total before tax = " + goodsTotal ); var newTotal = addVAT(goodsTotal); writeln("
total with tax added " + newTotal );
As can be seen, to make a function return a value we include a return statement after having done the appropriate calculation.
Arguments are named like variables (in fact they can be though of as a kind of local variable). So these named arguments can be referred to in the processing and calculation of the function.
The function below displays the current date and time:
//function name function today() //begin function statements { //declare variable dayAndTime // and initialise to become a new Date object var dayAndTime = new Date() //write date to browser page document.write("The date is: " + dayAndTime) //end function statements } //invoke function today()
This new String is sent to the write statement and displayed in the browser window.Open a new notepad document and write (or copy) the script for the today function. Save the document as "today.html" (or something similar) and load this HTML document into your Web browser. Your browser should look similar to the one in 14.4.4.
Your first task is to familiarise yourself with this function.
What does this new statement do? Save and reload your changed HTML file. You can find some
thoughts on this exercise at the end of the unit.
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:
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 following HTML code displays the text, the text boxes and the two buttons:
Calculation: Result:
var result = eval( theForm.expression.value); // put result into form field 'answer' theForm.answer.value = result; } //
Calculation: Result:
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.
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:
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 +):
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:
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.
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:
g
The calc() function is specified as follows:
The definition of the two functions follows:
function calc( theForm ) { // evaluate the text field expression; var result = eval( theForm.display.value );
Name (optional) append Arguments (optional) theForm, appString body theForm.display.value + appStrin Returns (optional)
Name (optional) calc Arguments (optional) theForm body var^ result^ =^ eval( theForm.display.value ); theForm.display.value = result; Returns (optional)
You can find a discussion of this activity at the end of the unit.
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.
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.
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.
An empty form field contains an empty String (i.e., "") as its value. Apart from seeing if the field's value is equal to the empty String, you can also test for an empty field by examining the length of the field's value. Since an empty field will have the empty String as its value, the length of the field's value will be zero.
Consider a page presenting the following form:
Let us assume that this form must have the first name and family name fields completed to be valid. The HTML
for the form is defined in a table. The form is named "order", and has an action to post the input values — replace [email protected] with your own email address if you wish to try out this form yourself.
First name:
The text First Name has been right aligned to improve layout and readability of the form. The input field has been named firstName — NAME="firstName"
orderform.firstName.value == ""
or we can test if the length of the value of this field is zero:
orderform.firstName.value.length == 0;
So if we wish our validateOrderForm() function to return true if the first name field has some value, and false otherwise we could write the function as follows:
function validate() { // at this point no invalid fields have been encountered var fieldsValid = true; // test field firstname var firstNameValue = orderform.firstName.value; if (firstNameValue.length == 0) { fieldsValid = false; } // return Boolean valid fields status return fieldsValid; }
As can be seen above, first the value of the firstName field is retrieved and assigned to a local variable called firstNameValue. Next, the length of this value is tested to see if it is zero. If it is, the Boolean variable fieldsValid is set to false to prevent the form from being submitted by making the function return false. Otherwise the value of this Boolean variable is left alone, and the function returns true.
If the first name field has had a value entered into, you may be informed that the form is about to be posted by the browser with a message such as the following:
The test we wrote for an empty text field is very useful for a page with many fields, so we can write a simple function called isEmpty() to do the test:
function isEmpty( fieldString ) { if fieldString.length == 0 return true; else return false; }
We can now rewrite the validate() function as follows:
function validate() { // at this point no invalid fields have been encountered var fieldsValid = true; // test field firstname if isEmpty( orderform.firstName.value ) { fieldsValid = false; } // return Boolean valid fields status return fieldsValid; }
While this works, the form is currently not very helpful to the user: if they click on the submit button and the first name field empty, nothing happens. At the very least the form should inform the user as to why it is not being submitted. This is easily solved by adding an alert statement, as in the following revised function definition:
function validate() { // at this point no invalid fields have been encountered var fieldsValid = true; // test field firstName
if ( isEmpty( orderform.firstName.value ) ) { alert( "First name must have a value - form not submitted" ); fieldsValid = false; } // return Boolean valid fields status return fieldsValid; }
Now if the submit button is pressed and the firstName field is empty, the form is not submitted, and the user is presented with the following dialog:
We can now extend our validate function to test the family name field as well:
function validate() { // at this point no invalid fields have been encountered var fieldsValid = true; // test field firstName