To call a JavaScript function when the onsubmit event occurs, you include onsubmit as an attribute of the tag, like this: In this example, the value assigned to onsubmit is a call to a
Trang 1return mylinks[(Math.floor(Math.random) * mylinks.length))];
}
The Completed Random Link Script with an Array
The following code shows the final version of the script, which incorporates all the changes
we've made in this exercise, including the MakeArray() constructor function, the creation of
the array of links, and the modifications to picklink()
<html>
<head>
<title>Random Link Generator</title>
<script language="JavaScript">
var mylinks = new Array("http://www.netscape.com/",
"http://www.lne.com/Web/",
"http://java.sun.com/",
"http://www.realaudio.com/",
"http://www.worlds.com/");
function picklink()
{
var linkselect = Math.floor(Math.random() * mylinks.length);
return (mylinks[linkselect]);
}
</script>
</head>
<body>
<h1>My random link generator</h1>
<p>Visit a
<a href="dummy.html" onClick="this.href=picklink()">randomly selected</a>
site from my list of favorites.</p>
</body>
</html
Tip
To add new links to your list, just add them to the list of arguments to the array
constructor
Trang 2Validating Forms with JavaScript
Remember the example form that you created back in Lesson 10, "Designing Forms?" It's shown again
in Figure 13.2 This form queries visitors for several pieces of information, including name, gender, and several bizarre options
Figure 13.2 The registration form.
[View full size image]
What happens when this form is submitted? In the real world, a script on the server side validates the data that the visitor entered, stores it in a database or file, and then thanks the visitor for her time
But what happens if a visitor doesn't fill out the form correctlyfor example, she doesn't enter her name
or choose a value for gender? The CGI script can check all that information and return an error But because all this checking has to be done on a different machine using a script, and because the data and the error messages have to be transmitted back and forth over the network, this process can be slow
Trang 3JavaScript enables you to do error checking on the browser side before the form is ever submitted to the server This saves time for both you and your visitors because everything is corrected on the visitors' side After the data actually gets to your script, it's more likely to be correct
Task: Exercise 13.4 Form Validation
Now take a look at how the registration form is validated with JavaScript Whenever you
click the Submit button on a form, two events are triggered in the browser: onclick and
onsubmit You're interested in the onsubmit event When the onsubmit event occurs, a
JavaScript function will be called to validate the form data
To call a JavaScript function when the onsubmit event occurs, you include onsubmit as an
attribute of the <form> tag, like this:
<form method="post"
action="http://www.example.com/cgi-bin/post-query"
onsubmit="return checkform(this)">
In this example, the value assigned to onsubmit is a call to a function named checkform()
which will be defined in a bit But first, the return statement at the beginning of the
onsubmit field and the this argument inside the parentheses in the checkform() function
need some further explanation
First, let's tackle this Whenever you call a function, you can send it a list of parameters,
such as numbers, strings, or other objects, by including them in the parentheses that
follow the function name In the preceding example, the this statement passes a reference
to the form object associated with the current form
Second, the return statement transmits a value back to the internal routine that called the
onsubmit event handler For example, if the checkform() function returns a value of false
after evaluating the form, the submission process will be halted as the return command
transmits this false value back to the submit event If the return statement was not
included in the event handler, the false value returned by the function would not be
received by the event handler, and the submission process would continue even if
problems were detected by the checkform() function
The Validation Script
As you've done before, define a <script> tag inside the <head> block and declare checkform
() as a function But this time, you also need to define a variable to hold a reference to the
form object sent by the calling function, as mentioned previously The code for the function
declaration looks like this:
<script language="JavaScript">
<! start script here
function checkform(thisform)
Trang 4The reference to the current form is given the name thisform by the function declaration
By accessing the thisform object, you can address all the fields, radio buttons, check
boxes, and buttons on the current form by treating each as a property of thisform
Having said this, you first want to test whether a name has been entered in the Name text box In the HTML code for this form, the <input> tag for this field is assigned a name
attribute of theName, like this:
<input type="text" name="theName" />
You use this name to reference the field as a child of thisform As a result, the field theName
can be referenced as thisform.theName, and its contents can be referenced as thisform theName.value
Using this information and an if test, you can test the contents of theName to see whether a name has been entered:
if (thisform.theName.value == null || thisform.theName.value == "")
{
alert ("Please enter your name");
thisform.theName.focus();
thisform.theName.select();
return false;
}
Note
The || operator (the or operator) shown in the if expression tells JavaScript
to execute the statements if either of the two tests is true
In the first line, thisform.theName.value is tested to see whether it contains a null value or
is empty ("") When a field is created and contains no information at all, it is said to
contain a null; this is different from being empty or containing just spaces If either of these situations is true, an alert() message is displayed (a pop-up dialog box with a
warning message), the cursor is repositioned in the field by thisform.theName.focus(), the field is highlighted by thisform.theName.select(), and the function is terminated by a
return statement that is assigned a value of false
If a name has been entered, the next step is to test whether a gender has been selected by checking the value of gender However, because all the elements in a radio button group have the same name, you need to treat them as an array As a result, you can test the
status value of the first radio button by using testform.gender[0].status, the second radio button by using testform.gender[1].status, and so on If a radio button element is
selected, the status returns a value of true; otherwise, it returns a value of false
Trang 5called selected and give it a value of false Now loop through all the elements using a for
loop; if the status of any radio button is true, set selected = true Finally, if selected still equals false after you finish the loop, display an alert() message and exit the function by calling return false The code required to perform these tests is shown here:
var selected = false ;
for (var i = 0; i <= 2 ; ++i)
{
if (thisform.gender[i].status == true)
{
selected = true;
}
}
if (selected == false)
{
alert ("Please choose your gender");
return false;
}
If both of the tests pass successfully, return a value of true to indicate that the form
submission should go ahead:
return true;
}
The Completed Registration Form with JavaScript Validation
When the JavaScript script that you just created is integrated with the original registration form document from Lesson 10, the result is a web form that tests its contents before they're transmitted to the CGI script for further processing This way, no data is sent to the CGI script until everything is correct If a problem occurs, the browser informs the user (see Figure 13.3)
Figure 13.3 An alert message.
So that you don't need to skip back to the exercise in Lesson 10 to obtain the HTML source used when creating the form, here's the completed form with the full JavaScript code
Trang 6<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Registration Form</title>
<script language="JavaScript">
<! start script here
function checkform(thisform)
{
if (thisform.name.value == null || thisform.name.value == "") {
alert ("Please enter your name");
thisform.name.focus();
thisform.name.select();
return false;
}
var selected = false ;
for (var i = 0; i <= 2 ; ++i)
{
if (thisform.gender[i].status == true)
{
selected = true;
}
}
if (selected == false)
{
alert ("Please choose your sex");
return false;
}
return true;
}
// End of script >
</script>
<style type="text/css">
body
{
background-color: #9c9;
}
input.required
{
width: 300px;
font: bold 12px Verdana;
background-color: #6a6;
border: solid 2px #000;
}
select.required
{
width: 300px;
font: bold 12px Verdana;
background-color: #6a6;
border: solid 2px #000;
}
td.required
{
font: bold 12px Verdana;
Trang 7{
width: 300px;
font: 12px Verdana;
background-color: #6a6;
border: solid 2px #999;
}
textarea.optional
{
width: 300px;
font: 12px Verdana;
background-color: #6a6;
border: solid 2px #666;
}
td.optional
{
font: 12px Verdana;
}
input.submit
{
background-color: #6a6;
border: solid 2px #000;
font: bold 12px Verdana;
}
</style>
</head>
<body>
<h1>Registration Form</h1>
<p>Please fill out the form below to register for our site Fields
with bold labels are required.</p>
<form action="/cgi-bin/register.cgi" method="post"
enctype="multipart/form-data" onsubmit="return checkform(this)">
<table>
<tr>
<td align="right" class="required"><b>Name:</b></td>
<td><input name="name" class="required" /></td>
</tr>
<tr>
<td align="right" class="required"><b>Gender:</b></td>
<td class="required">
<input type="radio" name="gender" value="male" /> male
<input type="radio" name="gender" value="female" /> female</td>
</tr>
<tr>
<td align="right" class="required">
<b>Operating System:</b></td>
<td>
<select name="os" class="required">
<option value="windows">Windows</option>
<option value="macos">Mac OS</option>
<option value="linux">Linux</option>
Trang 8<option value="other">Other </option>
</select>
</td>
</tr>
<tr>
<td valign="top" align="right" class="optional">Toys:</td>
<td class="optional">
<input type="checkbox" name="toy" value="digicam" /> Digital Camera<br />
<input type="checkbox" name="toy" value="mp3" /> MP3 Player<br />
<input type="checkbox" name="toy" value="wlan" /> Wireless LAN</td>
</tr>
<tr>
<td align="right" class="optional">Portrait:</td>
<td><input type="file" name="portrait" /></td>
</tr>
<tr>
<td valign="top" align="right" class="optional">
Mini Biography:</td>
<td>
<textarea name="bio" rows="6" cols="40" class="optional"></textarea>
</td>
</tr>
<tr>
<td colspan="2" align="right">
<input type="submit" value="register" class="submit" />
</td>
</tr>
</table>
</form>
</body>
</html>
Trang 9Creating an Image Rollover
Image rollovers are one of the most popular JavaScript applications around An image rollover is just an
image that is replaced by a different image when someone positions the mouse pointer over it Rollovers are often used with navigational elements to give viewers visual feedback indicating what will happen if they click on the image This technique is particularly useful when you have a number of navigational elements positioned close together, and you want to make it easier to see which element they'll be
clicking on
Task: Exercise 13.5 A JavaScript Image Rollover
In this example, we're going to create a page that contains an image that will be swapped
out when the pointer is moved over it Image rollovers are generally made up of three
components: an event handler associated with the image, a preload script to load the
image that's not displayed when the page loads, and a function that switches between the
two images Let's take a look at each of these components
Browser Detection
One big disadvantage of using JavaScript is that JavaScript works differently from browser
to browser A feature that exists in Firefox 1.5 might not exist in Microsoft Internet
Explorer 6.0 This problem is compounded by the fact that JavaScript capabilities change
from version to version of the browsers Originally, most people handled this problem by
determining which browser made the request and then turning on only those features that
worked with that browser Unfortunately, this was kind of an overly complex way to write
JavaScript code As new versions of browsers were released, all the JavaScript code with
browser detection had to be changed
Fortunately, a better technique is available Rather than relying on the inexact technique of
determining which browser the user is using, you can detect whether the actual object that
you want to manipulate exists and then base your functionality on that In this case, we
need to manipulate the document.images object, which contains information about all the
images used on the page The browser detection code that we use is very simple; it
consists of one statement:
if (document.images) {
// manipulate image object here
}
Any time you want to manipulate the images on the page, you wrap the code inside this if
statement If the browser acknowledges the existence of the document.images object, you
can manipulate that object
The Preload Script
When you add an image rollover to a web page, you should preload the images so that the
Trang 10first time the user moves the mouse over the rollover, the browser won't have to download the image before it can be displayed Preload scripts load the images into memory so that they can appear instantly when the pointer is positioned over the image that they will replace The preload script appears in the page header and simply creates new objects for all the images involved in the rollover This sample page contains only one image, so the preload code is very simple:
if (document.images) {
buttonOn = new Image();
buttonOn.src = "on.gif";
buttonOff = new Image();
buttonOff.src = "off.gif";
}
As you can see, the preload code is wrapped within the object detection code Two new images are created, one containing the "on" image and the other containing the "off"
image When the page loads, both of the image files assigned to the attributes of the
images will be downloaded
The Rollover Functions
Two functions are associated with an image rolloverone that replaces the "on" image with the "off" image, and another that replaces the "off" image with the "on" image In this example, the two functions are called activate and deactivate Here's the source code:
function activate(image_name) {
if (document.images) {
document[image_name].src = eval(image_name + "On.src");
}
}
function deactivate(image_name) {
if (document.images) {
document[image_name].src = eval(image_name + "Off.src");
}
}
Again, note that the object-detection code is used to protect users whose browsers don't allow the document's images to be manipulated using JavaScript Both of these functions accept a single parameter: the name of the image that will be swapped out In this
particular example, I could have hard-coded the image name into the script because
there's only one image on the page However, passing the image name is more useful to you because you'll be able to use these scripts with pages that contain multiple image rollovers
This is the most important code in the activate function:
document[image_name].src = eval(image_name + "On.src");
document[image_name] references the object on the page with the same name as the