CIS 207 Web Page Development - HTML

Chapter 9: JavaScript Objects and Events

In this tutorial, we will develop an online registration form on the effects of different feeding methods on newborn infants. The form will be interactive in that it will calculate items and check for entry mistakes.

Form Validation

Form validation is a process by which the server or the browser checks form entries to eliminate errors. When the server checks for errors, the form is sent to the server, checked, and a response is sent back to the browser. This is called server-side validation. Client-side validation occurs when the browser checks for errors and provides immediate feedback. JavaScript is ideally suited to provide client-side validation as a user enters data into a form.

Object-based Language

JavaScript is an object-based language, which means that the language is based on manipulating objects by either modifying their properties or applying methods to them. Objects are items that exist in a defined space on a web page. Each object has properties that describe its appearance, purpose, or behavior. An object can have methods, which are actions that can be performed with it or to it.

Consider an example of an oven in your kitchen. The oven is the object. It has certain properties, such as its model name, age, size, and color. There are certain methods you can perform with the oven object, such as turning on the grill. Some of these methods change the properties of the oven, such as the oven temperature.

Object
items that exist in a defined space
Properties
describe appearance, purpose, or behavior
Methods
actions that can be done
Oven model name
age
size
color
turn on the grill
turn on the self-cleaner
Car model name
age
color
crank engine
go forward
stop
Window name
status
default status
alert(message)
close()
document bgColor
fgColor
title
lastmodified
linkColor
write(string)
Be sure to understand Objects, Properties and Methods

The web browser itself is an object. The page you are viewing is an object. If the page has frames, each frame is an object. If the page has a form, the form is an object. Each field in the form is an object. These objects all have properties.

JavaScript Objects and Object Names

An object is identified by its object name, a name that JavaScript reserves for referring to a particular object.

See some of the common JavaScript Object, Properties, Methods and Event Handlers.

See Netscape's JavaScript Reference.

In order to use JavaScript to manipulate the current window, you use the object name "window". Use the object name "document" to affect the current web page. An object can also use a name that you've assigned to it with the NAME property in the <FORM>, <FRAME>, and <INPUT> tags.

In the tutorial, the form has the tag <FORM NAME=REG>, so we will refer to this form using the object name REG in our JavaScript program.

The topmost object in the hierarchy is the window object. Each object contains other objects. Sometimes you will need to specify this hierarchy when referring to an object. JavaScript uses a period (or dot) to separate each object. We start at the top of the hierarchy and move down. For example, the complete object reference for an input box named MEDRECNO which resides in the REG form of the current page would be:

window.document.REG.MEDRECNO

Note that object names are case sensitive. In most cases, you can omit the window object name from the hierarchy. Take a look at the following object references in the registration form in the tutorial.

Object Properties

Each JavaScript object has properties associated with it. There are certain key words that identify these properties. Here is a partial list of JavaScript objects and their properties.

(Note: Fig. 9-7 on page 9.10 has an error in the first item. They capitalized the D in defaultStatus.)

Object Name Property Name Description
window defaultStatus
frames
length
name
status
The default message displayed in the window's status bar
An array of all the frames in the window
The number of frames in the window
The target name of the window
A priority or temporary message in the window's status bar
frame document
length
name
The document displayed within the frame
The number of frames within the frame
The target name of the frame
history length The number of entries in the history list
navigator appCodeName
appName
appVersion
The code name of the browser
The name of the browser
The version of the browser
location href
protocol
The URL of the location
The protocol (HTTP, FTP, etc.) used by the location
document bgColor
fgColor
lastModified
linkColor
title
The page's background color
The color of text on the page
The date the document was last modified
The color of hyperlinks on the page
The title of the page
link href
target
The URL of the hyperlink
The target window of the hyperlink (if specified)
anchor name The name of the anchor
form action
length
method
name
The ACTION property of the <FORM> tag
The number of elements in the form
The METHOD property of the <FORM> tag
The name of the form

See Appendix D for a more comprehensive list.

There are several ways of working with properties. You can change the value of a property, store the property's value in a variable, or test whether the property equals a specified value in an If...Then expression.

Modifying a Property's Value

The syntax for changing the value of a property is:

object.property = expression

where object is the JavaScript name of the object you want to manipulate, property is a property of that object, and expression is a JavaScript expression that assigns a value to the property.

For example, we can change the background color to red with the JavaScript code:

document.bgcolor = "red";

And, we can change the foreground color (color of the type on the page) to white with:

document.fgColor = "white";

Also, we can add information to the status bar by setting the value of window.defaultStatus with:

window.defaultStatus = "Note on status bar at bottom...";

Click this example to see these codes in action.

Some properties are READ ONLY, which means that you can read the property value, but you can not modify it. One example is the appVerson property of the navigator object. We can read the value, but we can not change it.

The following code:

<script>
document.write("Browser code name is: "+navigator.appCodeName+"<br>");
document.write("Browser name is: "+navigator.appName+"<br>");
document.write("Browser version is: "+navigator.appVersion+"<br>");
</script>

produces the following output:

Assigning a Property to a Variable

Often, we will assign the value of a property, even read-only properties, to a variable in JavaScript. The syntax for assigning a property to a variable is:

variable = object.property;

where variable is the variable name, object is the name of the object, and property is the name of its property. For example, we can assign the appName property (name of the browser) to a variable named Browser with the following code - then, we can use the variable to reference this value.

<script>
Browser=navigator.appName;
document.write("The browser name is "+Browser+".");
</script>

Which will produce the following output:

Conditional Expressions

We can use a conditional expression to provide different code to visitors, depending upon their browser type. This is useful when we know that a certain feature we want to use, is different for each browser. The following code will react differently, depending upon which browser is being used to view the page.

<script>
if (navigator.appName == "Netscape") {
       document.write("<i><b>Netscape Navigator rules!! Alright!!!<br>");
       document.write("Go Netscape!!!</b></i>");
} else if (navigator.appName == "Microsoft Internet Explorer") {
       document.write("<i><b>Internet Explorer rules!! Way to go!!!<br>");
       document.write("Go Microsoft!!!</b></i>");
} else {
       document.write("<i><b>I don't know what browser you're using!</b></i>");
}
</script>

In this case, the above code produces the following output.

Note that the output depends upon the browser you are using to view this page. JavaScript checks to see what browser is being used, then it prints a different message based on what it found.

As we learned in the last chapter, we can use a simple IF statement to test a condition, or, we can use an IF statement with an ELSE clause. In this case, we needed more than one ELSE so we used ELSE IF for multiple ELSEs.

Let's look at a simple payroll example. If a worker works over 40 hours is a week, that worker will receive overtime pay. To determine if a worker is due overtime pay, we can check the hours entered to see if it is greater than 40. If it is greater than 40 hours, the worker gets overtime pay. However, if the hours entered are 40 hours or less, the worker does not get overtime pay. Check out a this IF...THEN example.

Object Methods

Methods are actions that objects can perform or actions that you can apply to objects. The syntax to apply a method to an object is:

object.method(parameters);        or simply         object.method();

where object is the name of the object, method is the method to be applied, and parameters are any values used in applying the method to the object. When we use multiple parameters, we separate each value with a comma.

Since JavaScript ignores HTML tags it encounters, we use the write method of the document object to send text or HTML codes to the browser from within the <SCRIPT> and </SCRIPT> tags with the following syntax:

document.write("<b>Bold Text</b>");

After inserting the <script> and </script> tags as follows:

<script>
document.write("<b>Bold Text</b>");
</script>

This example will print the following in the browser:

We can also use the submit() method of the form object to submit a form to a CGI script. And, we can make the browser go back to the previously visited page in the browser's history list by using the back() method of the history object. Here are some other JavaScript objects and methods associated with them.

Object Name Method Name Description
window alert(message)
close( )
prompt(message, text)
scroll(x,y)
Displays a dialog box with a message in the window
Closes the window
Displays a dialog box prompting user for information
Scrolls the (x,y) coordinate in the window
frame alert(message)
close( )
prompt(message, text)
Displays a dialog box with a message in the frame
Closes the frame
Displays a dialog box prompting user for information
history back( )
forward( )
Returns to the previous page in the history list
Goes to the next page in the history list
locationreload( ) Reloads the current page
documentwrite(text)
writeln(text)
Writes text and HTML tags to the current document
same as write, except that it inserts a line break
formreset( )
submit( )
Resets the form
Submits the form

See Appendix D for a more comprehensive list.

Pop Quiz 9.1 on page 9.14

Events

In JavaScript, an event is an action which occurs inside the browser to which JavaScript can respond. When an event is triggered or an event is "fired", the browser runs the block of code associated with that event. Events occur when the user clicks the mouse, submits a form, or moves the mouse. An event-handler is a JavaScript block of code which is associated with that event.

Here are some JavaScript events.

Event Description
AbortImage loading was aborted
BlurElement lost focus - occurs when user leaves a form field
ClickElement clicked on
Change Element's value changed
ErrorScript error has occured
FocusElement got focus - occurs when a window or form is made active

Other events include mousedown, mouseup, mouseover, mouseout, mousemove, dblclick, keydown, keyup, keypress, select, resize, dragdrop, reset, submit, load, unload, and move.

Event Handlers

An event handler is code added to an HTML tag that is run whenever a particular event is fired. The syntax for invoking an event handler is:

<tag event_handler="JavaScript commands">

where tag is the name of the HTML tag where the event occurs, event_handler is the name of an event handler, and JavaScript commands are the command(s) that call(s)s the JavaScript function which handles the event.

The names of event handlers usually start with "on" and continue with the name of the event handler. For example, the Click event uses the event handler name onClick and the blur event uses the event handleer name onBlur. Here's a list of several objects and their event handler names:

Object Names of Event Handlers
buttononClick
check boxonClick
documentonLoad, onUnload, onError
formonSubmit, onReset
framesonBlur, onFocus
hyperlinkonClick, onMouseOver, onMouseOut
imageonLoad, onError, onAbort
image map hotspot onMouseOver, onMouseOut
input boxonBlur, onChange, onFocus, onSelect
radio button onClick
reset button onClick
selection list onBlur, onChange, onFocus
submit button onClick
text area box onBlur, onChange, onFocus, onSelect
windowonLoad, onUnload, onBlur, onFocus

Take a look at these sample INPUT boxes. Try typing information in each of them. Try tabbing from one, to the next, and etc. Try clicking outside a box to make it lose focus after you've clicked in it to give it focus. Note the code below each box which causes the various events to be trapped and to provide the feedback.

First Input Box - no events
<input size="20">

Give Me FOCUS!  
<input onFocus='alert("I just got focus")' size="20">

Change Me!  
<input onChange='alert("I just got changed")' size="20">

Let Me Lose FOCUS!  
<input onBlur='alert("I just lost focus")' size="20">

All Three Together!  
<input onFocus='alert("Got focus")' onChange='alert("Got changed")' onBlur='alert("Lost focus")' size="20">


We can change the background color using radio buttons with the following code:

<form>
<input type="radio" name="chgclr" onClick="document.bgColor='red';">Red <br>
<input type="radio" name="chgclr" onClick="document.bgColor='blue';">Blue <br>
<input type="radio" name="chgclr" onClick="document.bgColor='yellow';">Yellow <br>
<input type="radio" name="chgclr" onClick="document.bgColor='white';">White (back to normal) <br>
</form>

Which will give the user the following choices. Click each one and try it out.

Red
Blue
Yellow
White (back to normal)


This button adds a message to the status bar:

<input type="button" name="clickme" value="Click Me"
onClick="window.status='You clicked it!'">

onLoad Event Handler

When a web page is loaded, it fires of the onLoad event handler. If we want something to happen whenever a page is loaded, we can create a function that is called when the page is loaded.

Have you ever visited a site that requires you to log in? Hopefully, the site used an onLoad event handler to give focus to the first input box when it loaded. If not, you would have to click on the input box with the mouse before you could enter your userID and password. That added step can be frustrating to experienced web surfers.

Click on this example to see a login screen WITHOUT focus starting with the first input box.

Now, try this - a login screen WITH focus starting with the first input box.

If you have a block of commands that you want to run when the page loads, you can call a function with:

<body onLoad="StartUpFunction();">

And, of course you would need to create the StartUpFunction( ) as we learned in the last chapter.

Emulating Events

We actually emulated an event in the previous login example. Our document.login.uid.focus(); command moved the cursor to the form named LOGIN and to the form element named UID to give it FOCUS.

We can add ( ) to an event name and we've got a new EVENT METHOD which we can use to perform an action. Any of the EVENT HANDLERS above can be modified by removing the ON and adding the ( ).

For example, to aggravate your visitors (which we would NEVER really do), we could create a command that would click the reset button after the visitor filled in the entire form, but just before they clicked the submit button. We could add the following code to the last input box which automatically clicks the RESET button to clear everything they entered:

<input onFocus="document.formname.resetme.click();">

NEVER DO THIS

Prompting User For Input

The prompt( ) method creates a dialog box containing a message, and an input field into which the user can type a value or text string. The syntax for the prompt( ) method is:

prompt("Message", "Default_Text");    the DEFAULT TEXT argument is optional

   OR   

variable = confirm("Message")    to set variable equal to what the user typed in the text box

where Message is the message that you want to appear in the dialog box, and Default_Text is the default text you want to appear in the dialog box's input field. For example, the following code:

<input type=submit value="Click Color"
onClick="prompt('What is your favorite color?','type color here');">

will create the following button:

This button is really useless since it does not capture the value that the user types into the dialog box. Also, the DEFAULT TEXT argument is optional, some browsers will require that you place two sets of quotes in place of the argument. For example:

prompt("Message", "");

will provide the prompt( ) dialog box without default text.

In most cases, you will want to capture the value that the user enters into the prompt( ) dialog box. If the user clicks the CANCEL button, the value returned will be null. We should plan for this possibility by using the IF condition to test for a null value. Also, there is a possibility that the user might click OK or press the ENTER key before typing in a color. In this case, the value returned will be an empty string (""). We should plan for this possibility as well. For example, we could use the following code:

<script>
function CheckColor() {
varColor = prompt("What is your favorite color?","");
if (varColor != null) {
       if (varColor == "") {
              alert("You left it blank!");
       } else {
              alert("I like the color "+varColor+" too!");
       }
}
}
</script>
<input type="submit" value="Click Color" onClick="CheckColor();">

to produce the following CLICK COLOR button which will respond back with the color if the user types in a color. It will respond back with a message saying that the user left it blank if they click OK or press ENTER without typing in a color. Finally, if the user clicks CANCEL, presses the ESCAPE key or clicks the CLOSE button on the dialog box, it will respond differently. It will simply close the box and not respond at all.

Calculated Fields

JavaScript treats values entered into input boxes as text strings. If you want to add, subtract, multiply or divide values entered into a text box, you have to convert the text string into a value with the eval( ) function. The eval( ) function can be used as follows:

<input name=fnum size="5">First number<br>
<input name=snum size="5">Second number<br>
<input name=total size="5">Total Added Together<br>
<input type=submit value="Add"
      onClick="total.value = eval(fnum.value) + eval(snum.value)">

To create the following three input boxes, the submit button, and allow the strings to be added together:

First number
Second number
Total Added Together

NOTE: If we did not use the EVAL( ) function to convert the strings entered into the text box, the strings would be concatenated or just combined together. For example the following code:

<input name=fnum2 size="5">First number<br>
<input name=snum2 size="5">Second number<br>
<input name=total2 size="5">Total Added Together<br>
<input type=submit value="Add"
      onClick="total2.value = fnum2.value + snum2.value">

Would create the following three input boxes, the submit button, but the strings will be concatenated not added. THE ONLY DIFFERENCE in this example is it is missing the EVAL( ) function.

First number
Second number
Total Added Together

Validating User Input

The THIS keyword is a word reserved by JavaScript to refer to the currently selected object. By using the THIS keyword, several different fields can call a function, and pass their information to the function. For example, instead of having to be specific to an exact field name to set its value to 2 as follows:

document.formname.FIELDNAME.value = 2;

If the FIELDNAME field is the current field, the following command will do the same thing:

this.value = 2;

This is extremely helpful if we have several fields that use the same function.

We can also pass information about the currently selected field to a function with the THIS keyword. For example, to set a field to zero when it receives focus, we could create one function as follows:

<script>
       function SetVal(field) {
       field.value = 0;
}
</script>

and call this one function each time a field receives focus with:

<input name="fieldONE" onFocus="SetVal(this);">
<input name="fieldTWO" onFocus="SetVal(this);">
<input name="fieldTHREE" onFocus="SetVal(this);">

Alert Dialog Box

The alert( ) method displays a dialog box containing a message and an OK button. The syntax for the alert( ) method is:

alert("Message");

where Message is the message that will appear in the alert dialog box. For example, the following code:

<input type="submit" value="Show Alert" onClick="alert('This field is required');">

will produce the following dialog box when the SHOW ALERT button below is clicked:

We would most likely place this alert dialog box on the onBlur( ) event handler of an input box object that we wanted to require that the user fill in.

Confirm Dialog Box

The confirm( ) method displays a message in a dialog box which has both an OK button and a CANCEL button. If the user clicks the OK button, the value TRUE is returned. If the user clicks the CANCEL button, the value FALSE is returned. The confirm( ) method is ideal when you want a simple YES or NO answer from a user. They syntax for the confirm( ) method is:

confirm("Message");

   OR   

variable = confirm("Message")   to set variable equal to the user's choice (true or false)

where Message is the message that will appear in the confirm dialog box. For example, the following code:

<input type="submit" value="Show Confirm"
onClick="answer=confirm('Submit Data?');alert('You answered '+answer);">

will produce the following dialog box when the SHOW CONFIRM button below is clicked:

If you clicked the OK button, an Alert( ) dialog box returns the value TRUE. If you click the CANCEL button, the Alert( ) dialog box returns the value FALSE.

We can combine the IF...THEN decision structure to the confirm( ) method to run a different block of code based on the user's response. The following code:

<script>
function CheckFudge() {
if (confirm("Do you want me to add hot fudge?")) {
       alert("OK, I will add hot fudge!");
} else {
       alert("OK, no hot fudge for you!");
}
}
</script>
<input type="submit" value="Check For Fudge" onClick="CheckFudge();">

will produce the following CHECK FOR FUDGE button that will first ask if you want hot fudge, then provide you different feedback in the form of an alert( ) dialog box, based on the choice you made. If you click OK, it will return TRUE and will respond with OK, I WILL ADD HOT FUDGE! If you click CANCEL, it will return FALSE and will respond with OK, NO HOT FUDGE FOR YOU!

PopUps

PopUps are the annoying additional windows that open automatically, usually just moments after a web page is opened. Many people solve the PopUp window problem by installing PopUp Killer - however, I understand that the publishers are no longer updating the program. There are a few good reasons web developers may want to open a PopUp window - the one that comes to mind is to offer visitors a printable version of your page when they request it by clicking a link for a printable version. Another is to display output from a calculation such as an amortization schedule.

The window object methods open() and close() are used to open and close PopUp windows. The syntax of the open method is:

window.open(url,windowName,features,replace)

where url is the URL of the file to be loaded into the new window, windowName is the name of the new window which allows you to later load another document into that window, features is a string (seperated with commas, and NO SPACES) that holds name value pairs to control the new window, and replace is an optional boolean value (True or False) which instructs the browser to replace the current history entry with the new one being loaded. Actually, all the parameters are optional. If the URL is omited, a new window window with about:blank will be displayed.

Here's an example. The following code (should be on one line, but it will not fit here):

<input type="submit" value="PopUp" onClick="window.open('http://www.halharris.com/198ln09.htm','MyPopUp','width=650,
height=400,scrollbars=yes,menubar=no,resizable=yes,status=no,toolbar=no')">

will produce the PopUp button which when clicked will create the PopUp window:

Be sure to use CAUTION in placing PopUps on your web page since many users consider them to be quite annoying!

Here are a few links for more information on PopUps:

Finally, if you decide you must use PopUps on your web page, AND you want your PopUps to load immediately when the user arrives at your web site, don't forget about the onLoad event handler of the window object.

Validating Form Submission

We can use the onSubmit event handler of the form object to call a function to validate user input with:

<form onSubmit="return ValidateFunctionName();">

The special keyword RETURN is used in this example since it will only submit the form if the function returns a value of TRUE. We will want to make certain that our ValidateFunctionName() in this example returns a value of TRUE or FALSE to indicate if the validation found entry errors. As you might have guessed, we will use the IF decision structure to check for various validation criteria we decide to use. If it validates successfully, without errors, we will add the line return true; and if it had errors, we'll add the line return false; .