Docsity

Chapter 16. JavaScript 3: Functions, Study notes of Design

Toggle sidebar
bg1
Chapter 16. JavaScript 3: Functions
Table of Contents
Objectives ...................................................................................................................................................................... 2
14.1 Introduction ........................................................................................................................................................ 2
14.1.1 Introduction to JavaScript Functions ........................................................................................................ 2
14.1.2 Uses of Functions ..................................................................................................................................... 2
14.2 Using Functions ................................................................................................................................................. 2
14.2.1 Using built-in functions ............................................................................................................................ 3
14.2.2 Using user-defined functions .................................................................................................................... 3
14.2.3 Defining and invoking a function in the same file .................................................................................... 3
14.2.4 Invoking a file defined in a different file .................................................................................................. 3
14.2.5 Executing code using 'eval' ....................................................................................................................... 4
14.3 Creating user-defined functions ......................................................................................................................... 4
14.3.1 A simple function to display the String “hello” ........................................................................................ 4
14.3.2 Creating a function using function statements .......................................................................................... 5
14.3.3 Creating a function using the 'Function()' constructor ............................................................................. 5
14.3.4 Creating a function using function literals ................................................................................................ 6
14.4 Some simple functions ....................................................................................................................................... 6
14.4.1 Mathematical functions ............................................................................................................................. 6
14.4.2 Functions that RETURN a value .............................................................................................................. 7
14.4.3 Defining a function that returns a value .................................................................................................... 8
14.4.4 A date Function ......................................................................................................................................... 8
14.4.5 The today function described .................................................................................................................... 9
14.5 Mathematical Functions ................................................................................................................................... 11
14.5.1 A form for calculations ........................................................................................................................... 11
14.5.2 A familiar calculator interface ................................................................................................................ 13
14.5.3 Some Function activities ......................................................................................................................... 15
14.6 Form Validation ............................................................................................................................................... 17
14.6.1 Testing for empty fields .......................................................................................................................... 17
14.6.2 The HTML defining the table ................................................................................................................. 17
14.6.3 The JavaScript function to validate the form fields ................................................................................ 18
14.6.4 Simplifying the code with a new function .............................................................................................. 19
14.6.5 Improving user interaction ...................................................................................................................... 20
14.6.6 Validation of multiple fields ................................................................................................................... 20
14.7 Testing for numeric fields ................................................................................................................................ 21
14.8 Testing for invalid field combination ............................................................................................................... 23
14.9 The remaining activities ................................................................................................................................... 27
14.9.1 Activity 6: Completing the colour model form ....................................................................................... 27
14.9.2 Activity 7: Avoiding Multiple Messages ................................................................................................ 27
14.10 Review Questions........................................................................................................................................ 28
14.10.1 Review Question 1 ............................................................................................................................. 28
14.10.2 Review Question 2 ............................................................................................................................. 28
14.10.3 Review Question 3 ............................................................................................................................. 28
14.10.4 Review Question 4 ............................................................................................................................. 29
14.11 Discussion Topic ......................................................................................................................................... 29
14.12 Extension: More complex functions............................................................................................................ 29
14.13 Discussions and Answers ............................................................................................................................ 31
14.13.1 Discussion of Exercise 1 .................................................................................................................... 31
14.13.2 Discussion of Activity 1 ..................................................................................................................... 31
14.13.3 Discussion of Activity 2 ..................................................................................................................... 32
14.13.4 Discussion of Activity 3 ..................................................................................................................... 32
14.13.5 Discussion of Activity 4 ..................................................................................................................... 32
14.13.6 Discussion of Activity 5 ..................................................................................................................... 33
14.13.7 Discussion of Activity 6 ..................................................................................................................... 33
14.13.8 Discussion of Activity 7 .................................................................................................................... 33
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25

Partial preview of the text

Download Chapter 16. JavaScript 3: Functions and more Study notes Design in PDF only on Docsity!

Chapter 16. JavaScript 3: Functions

  • Objectives Table of Contents
  • 14.1 Introduction........................................................................................................................................................
    • 14.1.1 Introduction to JavaScript Functions
    • 14.1.2 Uses of Functions
  • 14.2 Using Functions
    • 14.2.1 Using built-in functions
    • 14.2.2 Using user-defined functions
    • 14.2.3 Defining and invoking a function in the same file
    • 14.2.4 Invoking a file defined in a different file
    • 14.2.5 Executing code using 'eval'
  • 14.3 Creating user-defined functions
    • 14.3.1 A simple function to display the String “hello”
    • 14.3.2 Creating a function using function statements
    • 14.3.3 Creating a function using the 'Function()' constructor
    • 14.3.4 Creating a function using function literals
  • 14.4 Some simple functions
    • 14.4.1 Mathematical functions.............................................................................................................................
    • 14.4.2 Functions that RETURN a value
    • 14.4.3 Defining a function that returns a value
    • 14.4.4 A date Function.........................................................................................................................................
    • 14.4.5 The today function described
  • 14.5 Mathematical Functions
    • 14.5.1 A form for calculations
    • 14.5.2 A familiar calculator interface
    • 14.5.3 Some Function activities
  • 14.6 Form Validation
    • 14.6.1 Testing for empty fields
    • 14.6.2 The HTML defining the table
    • 14.6.3 The JavaScript function to validate the form fields
    • 14.6.4 Simplifying the code with a new function
    • 14.6.5 Improving user interaction
    • 14.6.6 Validation of multiple fields
  • 14.7 Testing for numeric fields
  • 14.8 Testing for invalid field combination...............................................................................................................
  • 14.9 The remaining activities
    • 14.9.1 Activity 6: Completing the colour model form
    • 14.9.2 Activity 7: Avoiding Multiple Messages
  • 14.10 Review Questions........................................................................................................................................
    • 14.10.1 Review Question
    • 14.10.2 Review Question
    • 14.10.3 Review Question
    • 14.10.4 Review Question
  • 14.11 Discussion Topic
  • 14.12 Extension: More complex functions............................................................................................................
  • 14.13 Discussions and Answers
    • 14.13.1 Discussion of Exercise
    • 14.13.2 Discussion of Activity
    • 14.13.3 Discussion of Activity
    • 14.13.4 Discussion of Activity
    • 14.13.5 Discussion of Activity
    • 14.13.6 Discussion of Activity
    • 14.13.7 Discussion of Activity
    • 14.13.8 Discussion of Activity

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

Objectives

At the end of this chapter you will be able to:

  • Understand the importance of functions;
  • Write HTML files using JavaScript functions;

14.1 Introduction

14.1.1 Introduction to JavaScript Functions

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.

14.1.2 Uses of Functions

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.

To Do

Read up about JavaScripts Functions in your textbook.

14.2 Using Functions

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.

14.2.5 Executing code using 'eval'

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:

14.3 Creating user-defined functions

14.3.1 A simple function to display the String “hello”

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).

14.3.2 Creating a function using function statements

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)

14.3.3 Creating a function using the 'Function()'

constructor

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()

Note: Function naming convention

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:

  • function calculateTaxTotal()
  • function changeImage()
  • function setCircleRadius()
  • function divide()

14.4.2 Functions that RETURN a value

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 value

Creating 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.

14.4.4 A date 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.

Exercise 1

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.

  1. Change all uses of the function name today() to an alternative name. Save and reload your changed HTML file.
  1. Change dayAndTime to an alternative name. Save and reload your changed HTML file.
  2. Add the window.status = dayAndTime; statement. Remember to use the new name you've given the dayAndTime variable name.

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.

14.5 Mathematical Functions

14.5.1 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:

Calculation: Result:

var result = eval( theForm.expression.value); // put result into form field 'answer' theForm.answer.value = result; } //

Calculation: Result:

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.

14.5.2 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:

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.

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:

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.

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.

14.6 Form Validation

14.6.1 Testing for empty fields

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:

14.6.4 Simplifying the code with a new function

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; }

14.6.5 Improving user interaction

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:

14.6.6 Validation of multiple fields

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