prog2002 topic 8 client-side development: dom and dom...

16
Topic 8 Client-side Development: DOM and DOM Manipulation Introduction This Topic examines attributes of the Document Object Model (DOM), which has been developed as an object based model for capturing and manipulating HTML and XML documents. You will see how JavaScript uses this model to access properties of document objects to both examine and change these objects dynamically. The Topic will also look at the event model used in HTML documents to trap events that occur in the document due to the user’s interaction with the displayed document and with the browser and also the browser’s interaction with the computer on which it is running. As always, it is essential that you complete all activities as directed in this study guide. Objectives On completion of the Topic, you should be able to: Explain the structure of the DOM (Document Object Model) and DOM2 Event Model Write JavaScript code to access any DOM object in a Web page; Write JavaScript code to process events that are triggered in a Web page; The Document Object Model Overview of DOM The Document Object Model (DOM) has been under development by the World Wide Web Consortium (W3C) since the mid 1990's and aims to provide an abstract model of HTML and XML documents. It is an abstract model designed to be used by many different programming languages so it is not specific to JavaScript at all. However, JavaScript’s interaction with HTML objects conforms to the DOM. Note that because JavaScript conforms closely to the DOM you will develop enough knowledge for easy transition to other programming languages (e.g. Java) that also conform to the DOM. It is also useful to note that the DOM is not just important to browsers. The current version of DOM is Level 3, which has not been fully developed. Level 1 (also known as DOM 0) focused closely on the HTML and XML model. DOM level 2 was issued in November 2000 and included event and style sheet models (at the time of writing is the latest approved version with DOM 3 under development). DOM 2 is (almost) completely supported by Firefox 2 (FX2), but Microsoft's Internet Explorer 7 (IE7) has its own naming conventions and leaves significant parts unimplemented or implemented in a non-standard way. DOM level 3 uses advanced XML features, document validation and formatting while expanding the event model to include event groups and key events. We will use DOM 2 features in this unit. Not all browsers support DOM 3 as yet. The DOM is applied to all XML and HTML documents resident on servers so that they can be processed before being displayed. The following code shows a table within an HTML document and the corresponding DOM structure. Figure 8.1 illustrates the relationship between them. PROG2002

Upload: others

Post on 11-May-2021

7 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: PROG2002 Topic 8 Client-side Development: DOM and DOM ...infotech.scu.edu.au/.../PROG2002_WD2...DOM_and_DOM_Manipulati… · DOM level 3 uses advanced XML features, document validation

Topic 8

Client-side Development: DOM and DOM Manipulation

Introduction

This Topic examines attributes of the Document Object Model (DOM), which has been developed

as an object based model for capturing and manipulating HTML and XML documents. You will see

how JavaScript uses this model to access properties of document objects to both examine and change

these objects dynamically. The Topic will also look at the event model used in HTML documents

to trap events that occur in the document due to the user’s interaction with the displayed document

and with the browser and also the browser’s interaction with the computer on which it is running.

As always, it is essential that you complete all activities as directed in this study guide.

Objectives

On completion of the Topic, you should be able to:

Explain the structure of the DOM (Document Object Model) and DOM2 Event Model

Write JavaScript code to access any DOM object in a Web page;

Write JavaScript code to process events that are triggered in a Web page;

The Document Object Model

Overview of DOM

The Document Object Model (DOM) has been under development by the World Wide Web

Consortium (W3C) since the mid 1990's and aims to provide an abstract model of HTML and XML

documents. It is an abstract model designed to be used by many different programming languages

so it is not specific to JavaScript at all. However, JavaScript’s interaction with HTML objects

conforms to the DOM. Note that because JavaScript conforms closely to the DOM you will develop

enough knowledge for easy transition to other programming languages (e.g. Java) that also conform

to the DOM. It is also useful to note that the DOM is not just important to browsers.

The current version of DOM is Level 3, which has not been fully developed. Level 1 (also known

as DOM 0) focused closely on the HTML and XML model. DOM level 2 was issued in November

2000 and included event and style sheet models (at the time of writing is the latest approved version

with DOM 3 under development). DOM 2 is (almost) completely supported by Firefox 2 (FX2), but

Microsoft's Internet Explorer 7 (IE7) has its own naming conventions and leaves significant parts

unimplemented or implemented in a non-standard way. DOM level 3 uses advanced XML features,

document validation and formatting while expanding the event model to include event groups and

key events. We will use DOM 2 features in this unit. Not all browsers support DOM 3 as yet.

The DOM is applied to all XML and HTML documents resident on servers so that they can be

processed before being displayed. The following code shows a table within an HTML document

and the corresponding DOM structure. Figure 8.1 illustrates the relationship between them.

PROG2002

Page 2: PROG2002 Topic 8 Client-side Development: DOM and DOM ...infotech.scu.edu.au/.../PROG2002_WD2...DOM_and_DOM_Manipulati… · DOM level 3 uses advanced XML features, document validation

CSC10217 Topic 8 - DOM and DOM Manipulation

Page 2

<!DOCTYPE html>

<html lang=”en”>

<head>

<meta charset=”utf8”>

<title> A simple Document </title>

</head>

<body>

<table width="200" border="4">

<tr>

<th> Breakfast </th>

<td> 0 </td>

<td> 1 </td>

</tr>

<tr>

<th> Lunch </th>

<td> 1 </td>

<td> 0 </td>

</tr>

</table>

</body>

</html>

Figure 8.1 DOM tree data structure of a simple document

The entire DOM will not be discussed in this Topic. We will select parts of the model that allow us

to use the JavaScript components, as we require them. In this section we will look at the overall

structure of the DOM and then look at the DOM naming scheme as it applies to JavaScript.

In DOM a document is modelled in a tree like data structure. The tree is made of HTML objects

represented by the tags in the document. Figure 8.1 shows the structure of a simple HTML document

that has a title and a table. You can see that the table is divided into two rows and the first of those

rows has header and a data element. Other nodes of the tree have been pruned to make the diagram

easier to follow.

Once there is tree structure, individual components can be identified using a similar technique to

JavaScript objects. For example, the name of the title object is document.title.

DOM example 8.1 - Window display

PROG2002

gcole
Rectangle
Page 3: PROG2002 Topic 8 Client-side Development: DOM and DOM ...infotech.scu.edu.au/.../PROG2002_WD2...DOM_and_DOM_Manipulati… · DOM level 3 uses advanced XML features, document validation

CSC10217 Topic 8 - DOM and DOM Manipulation

Page 3

Document Objects

All of the document objects start with the name document, which is of course an object itself. Object

names are used like any other objects in JavaScript. For example, a new title can be assigned to a

Web page using the following JavaScript assignment:

document.title= "This is a new title";

Most type of document objects can occur more than once in a document. This means you cannot

simply use the tag to access each object because it does not identify an object sufficiently. To provide

a unique name for an object you use the name parameter or the id parameter to a tag to provide it.

For example, look at the following simple form defined by the <form> tag:

<form name=testform>

<input type="text" name="data1" value = “Santa” /> <br />

<input type="text" name="data2" /> <br />

<input type="submit" name="submit" />

</form>

Each of the four objects has been assigned a name. The form is called testform, the two text

fields are called data1 and data2, and the submit button is called submit. Now you cannot just

use these names to access the objects.

The form elements are part of the form object just as the form object is part of the document object

so you must identify the form when you refer to the elements. This is the tree structure of the DOM.

Figure 8.2 shows the structure for this example form diagrammatically.

Figure 8.2 DOM tree structure for a simple form

To access the first data item you use the JavaScript name property that fully defines its position in

the tree, i.e. document.testform.data1. Before you can give an example of accessing one

of these objects you need to consider what you want to do with it. Each of the field objects has

several properties that have been set previously with parameters in the appropriate tag. To access

these properties the parameter name (in lower case) is used as a property of the HTML object. In

other words, the attributes are themselves objects contained in the HTML element object. For

example, to give some default text to a text field the value parameter to the tag is used as follows:

<input type="text" name="data1" value = "(text)" />

JavaScript can be used to do the same thing as follows:

document.testform.data1.value = "(text)";

In DOM 2 there is yet another way to reference an object in a document. If the object has an id

attribute then we can call the getElementById() method of the document object. To use

DOM 2 in a form requires both the name and id attributes for an object for example:

<form name = testform>

<document>

<item name = submit> <item name = data2>

da<document>

<item name = data1>

PROG2002

gcole
Rectangle
Page 4: PROG2002 Topic 8 Client-side Development: DOM and DOM ...infotech.scu.edu.au/.../PROG2002_WD2...DOM_and_DOM_Manipulati… · DOM level 3 uses advanced XML features, document validation

CSC10217 Topic 8 - DOM and DOM Manipulation

Page 4

<input type="text" name="data1" id=”data1” />

Why both? The name is required to send the name/value pair on submit and the id attribute is required

to use the DOM 2 as below

To make the previous assignment we could code in JavaScript:

document.getElementById("data1").value = "(text)";

As a second example, suppose we name a header with its id parameter as follows:

<h1 id="firstheader">Header 1</h1>

Its style object can be accessed as follows:

var h1style = document.getElementById("firstheader").style;

Note that care has to be taken when using DOM 2 features because some browsers don't completely

implement DOM 2.

Object Arrays

A final point with DOM naming in JavaScript is that you do not have to completely name all objects.

Objects such as table, forms, elements in a form, elements of table, etc.

can be accessed using array indexing. JavaScript calls the array the tag name is suffixed with an ‘s’,

e.g. tables, forms, elements, etc. To access the table required we simply use an array index, e.g.

document.tables[0] accesses the first table in the document and

document.testform.elements[1] accesses the second field in the testform.

Continuing the form example above (figure 4.3), we can change the default text of the second text

field to “(more text)” and change the text on the submit button with the following JavaScript code.

document.testform.elements[1].value="(more text)";

document.forms[0].submit.value="Push Me PLEASE";

Or, since all the objects have been named, this is equivalent to:

document.testform.data2.value="(more text)";

document.testform.submit.value="Push Me PLEASE";

The following activity asks you to go to the official DOM standards Web site. While it will give

you a good understanding of where the standards apply, if you download one of them you will find

that they are very difficult to understand.

Activity 8.1

Go to the http://www.w3c.org/ web site to see which DOM standard is the current one. Read

the general information about DOM.

Create an HTML document for the testform. Use JavaScript to assign values to the form as

showed above. Test your form to make sure it works as described.

DOM Events and Event Handlers

An event is the system’s notification (the browser’s notification in our case) that something has

occurred. In a graphical environment they can be any one of many events that can occur at any one

time. For example, the user could click on any one of a number of fields or widgets that are displayed

in the browser window. The user could resize the browser window or close it completely. There are

also external events from the Internet or from the computer in which the browser is running.

PROG2002

gcole
Rectangle
Page 5: PROG2002 Topic 8 Client-side Development: DOM and DOM ...infotech.scu.edu.au/.../PROG2002_WD2...DOM_and_DOM_Manipulati… · DOM level 3 uses advanced XML features, document validation

CSC10217 Topic 8 - DOM and DOM Manipulation

Page 5

To cope with all of these possibilities scripts called event handlers are written. An event handler is

associated with each event and JavaScript executes the event handler when each event occurs. For

example, some of the event handlers that will be written are triggered by changes in form controls.

They will check the content of form controls to make sure the user entered data in the correct format.

In JavaScript each event has a name, for example click, select and submit. These are

created as a user interacts with the HTML document. For example, the click event occurs when

a user clicks on document objects, the select event occurs when a user selects text in a text or text

area field, and the submit event occurs when the user clicks the submit button on a form.

Common DOM Events

onabort - invoked when the user aborts the loading of an image by clicking the STOP button

onclick - invoked when the user clicks the specified object

onfocus - invoked when the target object receives focus

onblur - invoked when the target object loses focus

onmouseover - invoked when the user passes the mouse over the target object

onmouseout - invoked when the mouse pointer leaves the target object

onsubmit - invoked when the user clicks the Submit button in a form

onchange - invoked when the user changes the contents of a text field

onselect - invoked when the user selects the contents of a text field

onreset - invoked when the user clicks the Reset button in a form

onload - invoked when the target image or document is loaded

onunload - invoked when the target image or document is unloaded

Types of Event handlers

Event handlers are associated with document objects in two different ways. The first is by specifying

the appropriate parameter to the tag that defines the object. Usually the parameter name is an event

name prefixed by “on”. For example, onclick, onselect and onsubmit are the tag

parameters used for the click, select and submit events respectively.

As an example of specifying event handlers, the following form definition instructs JavaScript to

execute the check_fields() function when the user clicks the submit button on a form:

<form action="http://spike.scu.edu.au/cgi-bin/echo_form"

method="post"

onsubmit=”check_fields()” >

Test the submit event handler.<br />

<input type="submit" value="Push Me" />

</form>

Here, the check_fields() function will have to be defined in the header of the document as

shown in the previous Topic. Notice how the event handler is attached to the <form> tag in this

case rather than the submit button tag.

Event handlers prefix an event name with ‘on’ onclick, onselect, onsubmit

onsubmit=check_fields()

The second way to specify event handlers is by using the DOM naming scheme to assign a function

name directly to the event handler object in the form object. In the DOM naming scheme the event

PROG2002

gcole
Rectangle
Page 6: PROG2002 Topic 8 Client-side Development: DOM and DOM ...infotech.scu.edu.au/.../PROG2002_WD2...DOM_and_DOM_Manipulati… · DOM level 3 uses advanced XML features, document validation

CSC10217 Topic 8 - DOM and DOM Manipulation

Page 6

handler is written in all lowercase letters but is the same name as the tag parameter technique above.

<form name = "testform"

action="http://spike.scu.edu.au/cgi-bin/echo_form"

method="post">

<p>Test the event handler.</p>

<input type="submit" value="Push Me" />

</form>

<script type="text/javascript">

<!--

document.testform.onsubmit = check_fields();

// -->

</script>

Event handlers assign a function name to an event handler with

document.testform.onsubmit = check_fields;

Note that there are advantages to both methods of assigning event handlers. The direct specification

of handlers allows the passing of parameters which is impossible in the second technique. For

example if the onsubmit was rewritten a: <form action="http://spike.scu.edu.au/cgi-bin/echo_form"

method="post"

onsubmit=”return check_fields()” >

The check_fields() function could return a boolean value (that would be specified in the

function). If the function returned a True value the form would be submitted, if the function returned

a False value the form would not be submitted to its action (and remain on screen). This will be

covered in further detail later in this topic.

The second technique however allows JavaScript to change the event handler after the page is loaded

which is occasionally useful in complex JavaScript pages.

As an example of another event handler consider the two events load and unload. These events are

triggered when a page completes loading and when the page is finished unloading (usually to be

replaced by another) respectively. They have the event handlers named onload and onunload

that are associated with the body of the document.

As an example of processing these events examine the following complete HTML document. It is

using the tag parameter technique to associate the event processors.

<!-- Using JavaScript event handlers -->

<head>

<title>onload and onunload</title>

<script type="text/javascript">

<!--

function load_alert() {

alert("page loaded");

}

function unload_alert() {

alert("page unloaded");

}

// -->

</script>

PROG2002

gcole
Rectangle
Page 7: PROG2002 Topic 8 Client-side Development: DOM and DOM ...infotech.scu.edu.au/.../PROG2002_WD2...DOM_and_DOM_Manipulati… · DOM level 3 uses advanced XML features, document validation

CSC10217 Topic 8 - DOM and DOM Manipulation

Page 7

</head>

<body onload=load_alert() onunload = unload_alert()>

Load and Unload alert messages.

</body>

To implement the same event handlers using the DOM name assignment method we would have the

same function definitions in the header of the document and code the body of the document as the

example following demonstrates.

<!-- Using DOM event handlers -->

<body>

<p>Load and Unload alert messages.</p>

<script type="text/javascript">

<!--

document.body.onload = load_alert;

document.body.onunload = unload_alert;

// -->

</script>

</body>

Notice that the <body> tag has been used for the document body. Since there is only one body

object we can use the tag name for the object name.

Activity 8.2:

a) Implement the above JavaScript event handlers for load and unload events using both

the methods shown above (parameters to tags and JavaScript object names).

b) Using a simple form, add an onclick event handler to the submit button. Make the handler

print a simple alert message so you can check it works (use the tag parameter technique).

c) Add an onresize event handler to the body of a simple HTML document. Make the

handler print a simple alert message so you can check it works when you change the size of

the browser window.

d) Write a form that submits two text boxes to

http://infotech.scu.edu.au/cgi-bin/echo_form - The form should not

allow itself to be submitted if the first text box is empty.

Form Events

In this section, event handlers for form processing will be examined. You may have noticed that

most of the events listed in the previous reading were closely related to forms. You will examine

the use of several of these in this section. Each control will be looked at separately because each has

its own properties. The focus and blur events that apply to all controls will then be examined.

Buttons <input type="button">

Buttons are a new form control(s) that are designed only for event handlers. They do not send any

information to a server. Their only purpose is to start JavaScript event handlers.

A button is created with a <input type= "button" /> tag inside a <form> tag. For example,

the following tag creates a button with the text “Push Me” on the button. It also defines an event

handler function button_pushed() for when the button is clicked.

<input type= "button" name="but1" value="Push Me"

PROG2002

gcole
Rectangle
Page 8: PROG2002 Topic 8 Client-side Development: DOM and DOM ...infotech.scu.edu.au/.../PROG2002_WD2...DOM_and_DOM_Manipulati… · DOM level 3 uses advanced XML features, document validation

CSC10217 Topic 8 - DOM and DOM Manipulation

Page 8

onclick="button_pushed()" />

As shown in the previous sections, a JavaScript event handling function can then be executed by

JavaScript, e.g.

function button_pushed() {

alert("Thank You!");

}

This event handler launches an alert dialog box with the simple message “Thank You!” displayed.

Activity 8.3:

a) Implement the above button and event handler. Test it.

b) Implement a button with text “Close Window”. In an attached event handler, execute the

JavaScript global function close() to close the browser window.

c) An onclick event handler can also be added to a hypertext link (the <a> tag). Create a

page with a link to another page that launches an alert message “Good Bye” when the user

clicks on the link.

Check boxes <input type=”checkbox”>

A checkbox object has a Boolean property called checked which signifies that the box is checked.

You will recall that the checked parameter is used to initially check the box when it is displayed.

You can test if the checkbox is checked by testing this attribute.

For example, look at the following form definition:

<form name="testform" action=””>

<p>Test checkbox</p>

<input type="checkbox" name="testcb" value="Y"

onclick=warning() />

</form>

This form assigns a JavaScript function warning() to the onclick event handler. Now suppose

you want to issue a warning if the box is checked. You can do this by testing the checked property

in the event handler. For example, the following JavaScript definition for the warning() function

will only issue a warning message if the box is checked.

function warning()

{

if (document.testform.testcb.checked)

alert("You've checked the box");

}

Notice how the full DOM naming scheme was used to identify the checkbox and the checked

property. You can also assign a new value to the checked property to change its status on the

screen. If you assign true to the checked property then it will become checked and if you assign

false then it will become unchecked.

In the following example form there are two checkboxes, one named testcb and the other named

friendcb. The first one has an event handler implemented.

PROG2002

gcole
Rectangle
Page 9: PROG2002 Topic 8 Client-side Development: DOM and DOM ...infotech.scu.edu.au/.../PROG2002_WD2...DOM_and_DOM_Manipulati… · DOM level 3 uses advanced XML features, document validation

CSC10217 Topic 8 - DOM and DOM Manipulation

Page 9

<!-- Example Checkbox -->

<form name="testform" action =””>

<p>Test checkbox 1</p>

<input type="checkbox" name="testcb" value="Y"

onclick=warning() />

<p>Friend checkbox</p>

<input type="checkbox" name="friendcb" value="Y" />

</form>

Now, you can test or change the status of the second checkbox inside the event handler for the first

checkbox. For example, the following JavaScript event handler checks the second box

(friendcb) if the first checkbox (testcb) becomes checked.

function warning()

{

if (document.testform.testcb.checked)

document.testform.friendcb.checked = true;

}

An alternative to setting the clicked property value is to call the click() member function. This

behaves exactly as if the user clicked on the object except that no event is triggered so no additional

event handlers are called. For example, you could rewrite the above event hander as:

function warning()

{

if (document.testform.testcb.checked)

document.testform.friendcb.click();

}

By specifying the full name of the control you can check and uncheck checkboxes from any event

handler in the document.

Activity 8.4:

a) Implement the second checkbox example with the testcb and friendcb. Test it.

b) Implement a button and a checkbox so pressing the button toggles the status of the checkbox,

i.e. when the button is pushed, if the box is checked then uncheck it and if the checkbox is

not checked then check it.

Radio Buttons <input type=”radio”>

Radio buttons are similar to checkboxes except for one major difference. You will recall that all

radio buttons in the one set of buttons are assigned the same name. This means that you cannot

check each of the buttons using the JavaScript name. There are two ways to approach this.

The first is to use the elements array object to access the radio buttons. The elements array object is

a property of the form object and contains one element for each control in the form. The form

elements are accessed using an array index.

An example radio form is as follows. It displays three radio buttons, each of which has a value of

“Red”, “Green” or “Blue”. All of the buttons have the same click event handle.

PROG2002

gcole
Rectangle
Page 10: PROG2002 Topic 8 Client-side Development: DOM and DOM ...infotech.scu.edu.au/.../PROG2002_WD2...DOM_and_DOM_Manipulati… · DOM level 3 uses advanced XML features, document validation

CSC10217 Topic 8 - DOM and DOM Manipulation

Page 10

<!-- Example Radio button form -->

<form name="testform" action=””>

<input type="radio" name="colour" value="Red"

checked="checked"

onclick=”button_pushed()” />Red<br />

<input type="radio" name="colour" value="Green"

onclick=”button_pushed()” />Green<br />

<input type="radio" name="colour" value="Blue"

onclick=”button_pushed()” />Blue<br />

</form>

Now, in the event hander each of the form elements must be tested to find out which one was clicked.

This can be done by defining the event handler as follows:

function button_pushed() {

var i=0;

while (i < document.testform.elements.length) {

if (document.testform.elements[i++].checked)

alert("You have selected" +

document.testform.elements[i].value);

i++;

}

}

This function loops through all the elements of the form, displaying the value of those it finds

checked. Luckily for those of you who do not want to use arrays, there is an alternative approach.

You can use a parameter in our event handler that signifies which button is pressed.

You can do this by defining the form as follows (the second approach):

<form name="testform" action=””>

<input type="radio" name="colour" value="Red"

checked="checked"

onclick=”button_pushed(‘Red’)” />Red<br />

<input type="radio" name="colour" value="Green"

onclick=”button_pushed(‘Green’)” />Green<br />

<input type="radio" name="colour" value="Blue"

onclick=”button_pushed(‘Blue’)” />Blue<br />

</form>

And you can define the event handler function as follows:

function button_pushed(col) {

if (col=="Red")

alert("You have selected Red");

if (col=="Green")

alert("You have selected Green");

if (col=="Blue")

alert("You have selected Blue");

Activity 8.5:

a) Implement the second radio button example above.

PROG2002

gcole
Rectangle
Page 11: PROG2002 Topic 8 Client-side Development: DOM and DOM ...infotech.scu.edu.au/.../PROG2002_WD2...DOM_and_DOM_Manipulati… · DOM level 3 uses advanced XML features, document validation

CSC10217 Topic 8 - DOM and DOM Manipulation

Page 11

b) Implement a new button in the Web page for part 1 labelled “Reset to Red” that selects the

“Red” radio button using an event handler.

Text fields (text, text area and password)

Text fields enable extra features to buttons such as default value, value, select(),

keydown, keyup and keypressed.

Text field objects have extra properties, methods and events to the button fields. Remember that,

although text fields are used in the examples here, the same properties and events apply to the

textarea and password fields.

The first property of text objects is the defaultvalue object. This contains the default text to be

displayed in the text object. The value contains the text entered by the user in the control as before.

The text object also has a select() method that can be called to highlight the text in text control.

This is useful to a user because it performs the same function as a user selecting all the text in the

text field with a mouse. This means that as soon as the user types a letter it replaces the text. This

is particularly useful when errors are detected in the text and the event handler that detected them

can select all of the text ready for the user to fix the error. Examples of this will not be looked at

until the focus event is examined later.

The change event is an additional useful event for text fields. This event is triggered when the user

leaves the text fields and the text has been changed from its previous value. This allows an event

handler to check that the changed text continues to be in the correct format.

The following example form calls an event handler each time a value changes in two text fields. In

the first it will call event handler check_num() which will check that the user has entered a number

and in the second it will call not_empty() which checks that the field is not empty.

<form name="testform" action=””>

<p>Enter a number:

<input type=text name=text1

onchange=”check_num()” /><br />

Enter some text:

<input type=text name=text2 value="."

onchange=”not_empty()” /></p>

</form>

The event handlers can be defined as follows:

function check_num()

{

var n = parseInt(document.testform.text1.value);

if ( isNaN(n) )

alert("This is not a number");

}

function not_empty()

{

if (document.testform.text2.value == "")

alert("This field must not be empty");

}

When you try this example you will see that, the browser continues with whatever action the user

PROG2002

gcole
Rectangle
Page 12: PROG2002 Topic 8 Client-side Development: DOM and DOM ...infotech.scu.edu.au/.../PROG2002_WD2...DOM_and_DOM_Manipulati… · DOM level 3 uses advanced XML features, document validation

CSC10217 Topic 8 - DOM and DOM Manipulation

Page 12

initiated to leave the field. You will see how to fix this problem later in case of errors. In this

example you can also see the use of the isNaN() function to check for a valid number. Note that

parseInt() returns a NaN value if the text cannot be turned into a number.

Text areas have three other events that you may like to investigate yourself. These are the

keydown, keyup and keypressed events. These react to individual key strokes with all three

events being triggered each time the user presses a key.

Activity 8.6:

Implement the above text form and test it. Make sure that you move between the fields several times

and try putting non-numeric text in the first field and delete all text in the second field.

Focus and Blur Events

A focus event occurs on a form object when the control becomes “live”. This means that the

control is the one that the user is interacting with the mouse or the keyboard. The blur event occurs

when the user leaves the control and moves on to do something else.

As an example of the focus event, we can attach an event handler to a text field as follows:

<input type="text" name="text1"

onfocus=”text1_instructions()” /><br />

As the name suggests, a JavaScript event handler can be implemented to give a message about what

is expected in the field. The message will appear at the time the user moves to the text field by

clicking on it or tabbing to it with the keyboard.

function text1_instructions()

{

alert("You must enter a number in this field");

}

Accompanying the focus event, there is a focus() method for each control that moves the user

focus to a particular field. This is very useful when processing errors because it can draw the user’s

attention to the field that contains the error. You will see an example of this shortly.

The blur event occurs when a control loses its focus. This is an ideal time for JavaScript to check

for errors in a control, e.g. check that a text field contains text of the expected format. For example,

you can rewrite the text field example from the previous section to use the onBlur event handler

as follows:

<form name="testform" action=””>

<p>Enter a number:

<input type="text" name="text1"

onblur=check_num() /><br />

Enter some text:

<input type="text" name="text2" value="."

onblur=not_empty() /></p>

</form>

You can implement the number check with the following JavaScript function:

<!-- Number check for Not a Number NaN -->

function check_num() {

var n = parseInt(document.testform.text1.value);

if ( isNaN(n) )

PROG2002

gcole
Rectangle
Page 13: PROG2002 Topic 8 Client-side Development: DOM and DOM ...infotech.scu.edu.au/.../PROG2002_WD2...DOM_and_DOM_Manipulati… · DOM level 3 uses advanced XML features, document validation

CSC10217 Topic 8 - DOM and DOM Manipulation

Page 13

{

alert("This is not a number");

document.testform.text1.focus();

document.testform.text1.select();

}

}

This function has added two extra JavaScript statements. The first calls the focus() member of

the text object to move the user’s focus back to the field in error (remember the user has moved focus

to trigger a blur event). The second calls the text object’s select() member to highlight the

text in the field (see previous section) so the user can easily change the text.

There is also a blur() method in each control object which forces the control to lose focus. As an

example of its use, look at the following event handler:

function skip_field()

{

alert("this field is disabled");

document.testform.text1.blur();

}

Suppose this is called on the focus event, for example with the following field definition:

<input type="text" name="text1"

onfocus=”skip_field()” /><br />

This event handler first launches an alert dialog box with a message and then caused the browser to

move onto the next field in the form. The user will never be able to enter text in this field.

Submit Button <input type=”submit”>

There is a final technique to look at for processing fields in a form with JavaScript events. It is

common for all processing to be left until the submit button is pressed. The processing can then be

delayed until the submit event occurs. As errors are detected the event handler can move to the

offending field by calling the appropriate focus() member so the error can be fixed. When this

type of error processing is used the user has more time to realise there is an error and then attempt

to correct it before the error processing occurs. As an example of the submit processing, we can add

a submit button to the example above and attach an onsubmit event handler as follows.

<form name="testform"

onsubmit="return check_form()"

action="http://infotech.scu.edu.au/cgi-bin/echo_form"

method="post">

<p>Enter a number:

<input type="text" name="text1" /><br />

Enter some text:

<input type="text" name="text2" value="." /><br />

<input type="submit" value="Submit Form" /></p>

</form>

Notice how the event handlers have been removed from individual fields and attached a single event

handler to the form object to handle submit events. Now this event handler is different from previous

examples. It is specified as the string "return check_form()". Previously the function call

has just been included but now the return keyword has also been included. This is necessary

PROG2002

gcole
Rectangle
Page 14: PROG2002 Topic 8 Client-side Development: DOM and DOM ...infotech.scu.edu.au/.../PROG2002_WD2...DOM_and_DOM_Manipulati… · DOM level 3 uses advanced XML features, document validation

CSC10217 Topic 8 - DOM and DOM Manipulation

Page 14

when a result needs to be returned to JavaScript from our event handler. In this case a Boolean value

needs to be returned, to signal the browser whether to send the data to the server or not.

Note that if you use the DOM object method to assign an event handler then you do not need to insert

a return keyword. You could attach the same event handler using the following JavaScript command.

document.testform.onsubmit=check_form();

The following event handler processes the form when the submit button is clicked.

function check_form()

{

var n = parseInt(document.testform.text1.value);

if ( isNaN(n) )

{

alert("This is not a number");

document.testform.text1.focus();

document.testform.text1.select();

return false;

}

if (document.testform.text2.value == "")

{

alert("This field must not be empty");

document.testform.text2.focus();

document.testform.text2.select();

return false;

}

return true;

}

This event handler checks the fields in the same way as the previous ones. If it finds an error it sends

an alert to the user and sets the focus on the field in error. Because the two controls in the form are

text fields, it then selects the text to make it easier for the user to change. This event handler then

terminates the function and returns the Boolean value false on both errors. The value false

indicates to the browser that the form data should not be sent to the server. If neither field is in error

then the final return statement is executed returning a true value. When the browser receives this

value it proceeds to send the form data to the server.

There are many variations on how to use event handlers to interact with forms. You are asked to

implement your own form checking in the activities.

Activity 8.7:

a) Implement a form that uses the onFocus event to prevent a user from entering information

to a text box.

b) Implement the above form that checks the two text fields when the submit button is clicked.

Make sure it only sends the data to the CGI server when the fields are both correct.

c) Develop a new form (without a submit button) that displays a text field and three radio

buttons labelled “Large”, “Medium”, “Small”. As the user clicks on each of these update

the text field to display the text “large”, “medium” and “small”. Disable the text field so the

user cannot gain its focus (this was described at the start of this section).

PROG2002

gcole
Rectangle
Page 15: PROG2002 Topic 8 Client-side Development: DOM and DOM ...infotech.scu.edu.au/.../PROG2002_WD2...DOM_and_DOM_Manipulati… · DOM level 3 uses advanced XML features, document validation

CSC10217 Topic 8 - DOM and DOM Manipulation

Page 15

The Navigator Object

As mentioned before, support for various components of JavaScript, CSS, HTML and other

components of the Web vary between browsers. This means that your Web pages may not work on

every user’s browser. This is particularly so if you're JavaScript contains the latest features from

one of the browser manufacturers.

To allow your JavaScript to check on the abilities of the browser in which your Web page has loaded

the navigator object is provided. The following table summarises some of the useful properties

of the navigator object.

Property Name Contents

appName name of browser

appVersion version number of browser

mimeTypes an array of MimeType objects supported either by the browser

or by its plug-ins or helper applications

platform the machine that the browser was compiled for (e.g. “Win32”)

plugins array of Plugin objects installed in the browser

This object can be used to display the name, version and platform such as: document.write("application: " + navigator.appName + "<br />");

document.write("version: " + navigator.appVersion + "<br />");

document.write("for platform: " + navigator.platform + "<br />");

Activity 8.8:

Implement the above Web page to check your own browser version.

Assignment advice

In this week you continue working on version-2 of the movie_zone application. You will work on

completing the View and Model modules. You will also need to continue building the user interface

for the application. By the end of this week, you should have the interface layout with all required

input forms. You can start incorporating JavaScript in your input forms for testing. Note that all

JavaScript code must be place in separate JavaScript files.

Summary

In this topic, you looked at the structure of the Document Object Model (DOM) and saw how

JavaScript uses this model to access attributes of objects in HTML Web pages. You have used

JavaScript to handle events in Web pages such as mouse clicks, keyboard activity and other browser

activity. In particular, you looked at how you can use events to check a user’s data input in an HTML

form. You used the click event to call JavaScript functions when submit, reset, checkboxes, radio

and plain buttons are pushed. You checked text, textarea and password fields by processing the

change event which is triggered when the user changes text in a field. You also used the focus

and blur events that occur as the user goes to a control and leaves a control. You also saw how

you can delay form checking until the submit event is triggered by the form’s submit button.

Finally in this Topic you used the navigator object to identify different browser versions where

the Web page is loaded. It was noted that you can use this object to code different HTML depending

on the type of browser in use.

PROG2002

gcole
Rectangle
Page 16: PROG2002 Topic 8 Client-side Development: DOM and DOM ...infotech.scu.edu.au/.../PROG2002_WD2...DOM_and_DOM_Manipulati… · DOM level 3 uses advanced XML features, document validation

CSC10217 Topic 8 - DOM and DOM Manipulation

Page 16

References

JavaScript Tutorial. [ONLINE] Available at: https://www.tutorialspoint.com/javascript/index.htm.

[Accessed 09 April 2018].

JavaScript Tutorial. [ONLINE] Available at: https://www.w3schools.com/js/default.asp. [Accessed

09 April 2018].

PROG2002

gcole
Rectangle