Chapter 7
Real-Life Examples I
CONTENTS
This chapter includes several example JavaScript applications
that apply the techniques you learned in Part II, "Using
JavaScript Objects and Forms." These include the following:
- Example 1: Displaying a Pop-Up Message: A page that
includes an "instructions" link, which opens a small
window to display the instructions.
- Example 2: Displaying Random Quotations: An example
of a method of displaying a different quotation each time the
user loads the page.
- Example 3: A Validated Registration Form: An example
of a registration form for a commercial Web site, including validation
for key fields.
One thing lacking in HTML is a method of including pop-up messages.
These messages appear in a small window and go away when you click
on them or perform another action. This could be useful for a
disclaimer, brief instructions, or anything you want to display
to the user quickly without leaving the current page.
The following techniques are used in this example:
- Defining and using a function (Chapter 3)
- Using an event handler to trigger an action (Chapter 3)
- Creating a new window and controlling its appearance (Chapter
5)
- Using the window object's
close() method (Chapters
3 and 5)
For this example, let's create a link to the word instructions
on a Web page. Clicking this link will pop up a window with some
brief instructions; you can then click a button in that window
or move the focus to the main window, and the window will disappear.
You could create a simple pop-up message using a JavaScript alert,
but this isn't perfect-for starters, it includes the nonfriendly
message "JavaScript Alert:"
at the top. It also uses plain text; your pop-up instructions
can include boldface, italics, and anything else supported by
HTML.
The main HTML document for the pop-up window example is Listing
7.1. This is the main page, and it includes a link to the word
instructions to display the
pop-up instructions.
Listing 7.1. (POPUP.asp) The main HTML document for the pop-up
window example.
<HTML>
<HEAD><TITLE>Pop-up Messages</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function instruct() {
iwin = window.open("instruct.asp","IWIN",
"status=no,toolbar=no,location=no,menu=no,width=400,height=300");
}
</SCRIPT>
</HEAD>
<BODY>
<H1>Pop-up Message Test</H1>
<HR>
This page demonstrates the use of a pop-up window. The window is
created when the link below is clicked, and disappears when the OK
button is pressed.
<HR>
Before you continue with this page, please take a quick
look at the
<A HREF="#" onClick="instruct();">
instructions</A>.
<HR>
The page continues...
</BODY>
</HTML>
The word instructions is
a link. To avoid sending the user to an actual destination, this
listing uses # as the link
destination. The actual work for this link is done by the event
handler, which calls the instruct()
function.
The instruct() function is
defined in the header. It includes the command to create the new
window, specifying INSTRUCT.asp
as the document to be loaded into the new window. The window attributes
are set to turn off the status line, menu bar, toolbar, and other
features, and set the window size.
The second HTML document, shown in Listing 7.2, is the document
containing the actual instructions. This document also includes
a bit of JavaScript-the OK button is defined with an event handler
to close the window.
Listing 7.2. (INSTRUCT.asp) The second HTML document for the
pop-up window example.
<HTML>
<HEAD><TITLE>Instructions</TITLE>
</HEAD>
<BODY>
<H1>Instructions</H1>
These are the instructions. This is actually a separate HTML
document, INSTRUCT.asp. This can include <b>bold</b>,
<i>italic</i>, and other HTML features, since it's an ordinary
HTML document. Click the button below to return.
<FORM NAME="form1">
<INPUT TYPE="button" VALUE="OK"
onClick="window.close();">
</FORM>
</BODY>
</HTML>
Figure 7.1 shows this example in action, with the instructions
window displayed. Here are a few interesting observations about
this example:
Figure 7.1 : The pop-up window example in action.
- One potential problem could be caused if the user doesn't
click on the OK button in the instructions window. The window
will remain open. One solution is to use the onUnload
event handler to close the instructions window when the main window
closes.
- Notice that although the new window you created is called
iwin, it is referred to in
INSTRUCT.asp as simply window.
This is because for this document, the instructions window is
the current window.
- You have control over the appearance of the new window, but
not complete control-for example, the title bar cannot be turned
off. This is partially due to cross-platform issues; not all GUIs
support a window with no title.
One of the things that keeps users coming back to a good Web page
is variety-something different every time they visit. Using JavaScript,
you can add a random quotation, a random link, or a random tip
to the page.
For this example, let's display a random quotation at the top
of a Web page. This example illustrates the following techniques:
- Using the Math object's
methods (Chapter 4)
- Creating arrays and storing data (Chapter 4)
- Creating HTML "on the fly" with the document.write
method (Chapter 5)
You will embed the script to generate random quotations in the
body of the Web page with the <SCRIPT>
tag. Listing 7.3 is the HTML document, including the JavaScript
program.
Note |
This script uses the Math.random() method, which wasn't supported for all platforms until Netscape 3.0b3. Be sure you try it with the most recent version.
|
Listing 7.3. (RANDQUOT.asp) The HTML document for the random
quotations example.
<HTML>
<HEAD><TITLE>Random Quotations</TITLE>
</HEAD>
<BODY>
<H1>Random Quotations</H1>
<HR>
<SCRIPT LANGUAGE="JavaScript">
//store the quotations in arrays
quotes = new Array(6);
authors = new Array(6);
quotes[0] = "I have a new philosophy. I'm only going to dread one day at a
time.";
authors[0] = "Charles Schulz";
quotes[1] = "Reality is the leading cause of stress for those in touch with
it.";
authors[1] = "Jack Wagner";
quotes[2] = "Few things are harder to put up with than the annoyance of a good
example.";
authors[2] = "Mark Twain";
quotes[3] = "The pure and simple truth is rarely pure and never simple.";
authors[3] = "Oscar Wilde";
quotes[4] = "There's no business like show business, but there are several
businesses like accounting.";
authors[4] = "David Letterman";
quotes[5] = "Man invented language to satisfy his deep need to complain.";
authors[5] = "Lily Tomlin";
//calculate a random index
index = Math.floor(Math.random() * quotes.length);
//display the quotation
document.write("<DL>\n");
document.write("<DT>" + "\"" + quotes[index] + "\"\n");
document.write("<DD>" + "- " + authors[index] + "\n");
document.write("</DL>\n");
//done
</SCRIPT>
<HR>
The quotation above was generated randomly when you loaded this page.
Reload for another one, or cheat-view the source code and see them all.
<HR>
</BODY>
</HTML>
This example uses two arrays, quotes
and authors, to store the
quotations. Notice that an array can hold more than just numbers-in
this case, each array element is a string.
To select a random quotation, you use Math.random()
to produce a random number between 0 and 1. You then multiply
it by the number of quotations, provided by the length
property of the array, to produce a number in the right range.
All this is enclosed in the Math.floor
function, which removes the fractional part of the result.
Figure 7.2 shows the output of this example. Here are a few observations
and notes about this program:
Figure 7.2 : The output of the random quotations example.
- I've used this example to display a random humorous quotation.
You could substitute tips about the current page, short advertisements
about the company, or even random links-you can include HTML within
the array elements without causing a problem.
- There are only six quotations in this example-to keep things
short. You could easily add more; just continue with quotes[6]
and so on. Be aware that this is within the HTML source, though,
so the more available quotes, the slower the user's access to
the page. Just for fun, I've included a version of this program
with over 100 quotations on the CD-ROM.
- Notice that there are two arrays, one for quotations and one
for authors. An object-oriented alternative is to create a new
object with two string properties, then store an object in each
array element. For example, you could create a Quotation
object with author and quote
properties. You might find this useful if you have more than two
parts for each of your random items.
Many Web pages-especially commercial ones, or services you pay
for-include some sort of registration form so that users can submit
information about themselves. For this example, let's create a
registration form, including validation with JavaScript.
This example illustrates the following techniques:
- Using string objects (Chapter 4)
- Building and validating forms (Chapter 6)
- Using the mailto: method
to get results from a form without using CGI (Chapter 6)
As with the examples in Chapter 6 "Using Interactive Forms,"
you need to include the functions to validate the form in the
header of the HTML document. The HTML source for the validated
registration form is shown in Listing 7.4.
Listing 7.4. The HTML source code for the validated registration
form.
<HTML>
<HEAD><TITLE>Registration Form</TITLE>
<SCRIPT>
//global variable for error flag
var errfound = false;
//function to validate by length
function ValidLength(item, len) {
return (item.length >= len);
}
//function to validate an email address
function ValidEmail(item) {
if (!ValidLength(item, 5)) return false;
if (item.indexOf ('@', 0) == -1) return false;
return true;
}
// display an error alert
function error(elem, text) {
// abort if we already found an error
if (errfound) return;
window.alert(text);
elem.select();
elem.focus();
errfound = true;
}
// main validation function
function Validate() {
errfound = false;
if (!ValidLength(document.regform.username.value,6))
error(document.regform.username,"Invalid Name");
if (!ValidLength(document.regform.phone.value,10))
error(document.regform.phone,"Invalid phone number");
if (!ValidEmail(document.regform.email.value))
error(document.regform.email, "Invalid Email Address");
if (!ValidLength(document.regform.address.value,10))
error(document.regform.address, "Invalid Mailing Address");
if (!ValidLength(document.regform.city.value,15))
error(document.regform.city, "Invalid City/State/Zip");
return !errfound; /* true if there are no errors */
}
</SCRIPT>
</HEAD>
<BODY>
<H1>Registration Form</H1>
<HR>
Please fill out the fields below to register for our web page. Press the
Submit button at the end of the form when done.
<HR>
<FORM NAME="regform" onSubmit="return Validate();"
ACTION="mailto:username@host" METHOD="post">
<B>Your Name:</B>
<INPUT TYPE="text" NAME="username" SIZE=20><BR>
<B>Your Phone Number: </B>
<INPUT TYPE="text" NAME="phone" SIZE=15><BR>
<B>E-mail address:</B>
<INPUT TYPE="text" NAME="email" SIZE=20><BR>
<B>Mailing address:</B>
<INPUT TYPE="text" NAME="address" SIZE=30><BR>
<B>City, State, Zip:</B>
<INPUT TYPE="text" NAME="city" SIZE=30>
<HR>
<INPUT TYPE="SUBMIT" NAME="submit" VALUE="Submit Registration">
<INPUT TYPE="RESET" VALUE="Start Over">
</FORM>
</BODY>
</HTML>
This application includes several functions:
- Validate() validates
the fields of the form and returns true or false depending on
whether any errors were found. The user's name, phone number,
e-mail address, and mailing address are all validated.
- error() displays an appropriate
error message when a field is invalid.
- ValidLength() is used
to verify that the text the user entered into a field is greater
than a certain length. This is used for most of the fields.
- ValidEmail() validates
an e-mail address. It checks for a total length greater than five
characters and makes sure an "at" sign (@)
appears somewhere in the text.
Netscape's view of this form is shown in Figure 7.3. In the figure,
an invalid e-mail address has been entered, and an alert is being
displayed with the error message.
Figure 7.3 : The validated registration form in action.
The mailto: action is used
to submit the data. (Be sure to replace user@host
with your e-mail address.) If the user submits the form and validation
is successful, a simple e-mail message is sent with the information
from each of the fields. An example of such a message is shown
in Listing 7.5.
Listing 7.5. The e-mail message sent as a result of the registration
form.
username=Michael+Moncur&phone=555-555-2314
&email=guides@starlingtech.com
&address=234+Elm+Street
&city=Anywhere%2C+USA+44444
&submit=Submit+Registration
As you can see, this doesn't exactly come back in English. It's
even worse than you think-I added the line breaks in the listing.
Nevertheless, you can read the results. Software is also available
to read it automatically.
The encoding in Listing 7.5 is called URL encoding and is used
when data is sent to a CGI script. You'll look at this process
in detail in Chapter 17, "Combining JavaScript, CGI, and
SSI."
|