Early Web sites consisted of many of the same Web page elements we use today: forms, images, hyperlinks, and static text. They also consisted of small applications called applets that ran inside the Web page and were written in a new programming language called Java. In 1995, Netscape Communications added Java support to its flagship product, Netscape Navigator. However, Netscape was painfully aware that many Web site developers were not Java developers, so it needed to find a way to allow non-Java developers to interact with Java applets on Web pages. It did so with the introduction of LiveScript, a technology that was renamed JavaScript by the time it made it into Netscape Navigator 2.0.
Web developers were quick to embrace JavaScript, but it was not used the way Netscape intended. It was mainly used to provide programmatic access to page content such as forms, images, and text, not to script Java applets. In fact, the most common use for JavaScript at the time is still one of its most common uses today—image swapping. Mouse rollovers were starting to appear all over the Internet.
At the same time, Microsoft released Internet Explorer 3.0, a major upgrade to its less-than-stellar Web browser. With the release of Internet Explorer 3.0, Microsoft unveiled its own flavor of JavaScript coined JScript. Microsoft also added its own scripting language (VBScript) and support for a new and emerging technology—Cascading Style Sheets, or CSS. The inclusion of CSS support did not buy Microsoft much, however. Microsoft’s JScript implementation did not include support for image swapping, and that made it useless in the eyes of Web developers. Developers started writing scripts that checked browser versions, and if they detected Internet Explorer, they simply did not attempt to present any of the new dynamic content scripting provided.
Around this same time, Web developers began writing scripts to check for Netscape browsers by seeing if the browser identified itself as “Mozilla,” an identifier that Netscape Navigator used at the time. As browsers added functionality, they all began to identify themselves as “Mozilla Compatible” so that scripts would work successfully. Even today, you will see all browsers identified as Mozilla if you review server logs for your Web site.
Microsoft reacted with the release of Internet Explorer 3.02. Internet Explorer 3.02 added, among other things, support for image swapping. It also continued the divergence of scripting implementation among the major players in the Web browser world. Web developers were still not able to write a script that would easily run on any browser. Instead, they had to write a version of their scripts for each browser and use the appropriate one depending on which browser was being used to access their page. The Web developer community was aching for standards to be introduced to alleviate this problem. Sound familiar?
Netscape and Sun Microsystems, assisted by the European Computer Manufacturers Association (ECMA), standardized browser scripting with the release of ECMAScript in 1998. Ironically, Netscape was also in the process of releasing Netscape Navigator 4.0, a browser that would bring a completely proprietary document object model with it. Microsoft did the same with the release of Internet Explorer 4.0. These 4.0 series browsers introduced a robust new method of programming Web pages called Dynamic HTML (DHTML), a combination of HTML, CSS, and scripting. However, they also widened the gap in compatibility between the two browsers. ECMAScript was too late to stop the momentum.
→ | For more information on DHTML, see “The Document Object Model” section in this chapter, p. 422. |
The majority of client-side scripting on the Internet today is used to script DHTML effects in Web pages. While Internet Explorer still supports VBScript as a scripting language, the vast majority of Web developers use JavaScript and not VBScript because it will work in all major browsers. For that reason, this chapter sticks to a discussion of JavaScript.
Expression Web 2 provides tools such as behaviors and interactive buttons that can generate JavaScript code for you. However, if you find that you want to add more robust scripts to your page or modify the scripts Expression Web 2 generates—or if the scripts Expression Web 2 generates don’t perform the task you need—knowing how to write JavaScript is a vital skill to have.
The purpose of this chapter is not to teach you how to be a JavaScript programmer. Instead, it is intended to give you a taste of what client-side scripting can be used for and the basics of how it is used. If you are interested in learning how to take maximum advantage of this powerful technology, you should pick up a book specifically with that purpose in mind.
→ | For a comprehensive discussion of JavaScript and how to use it to make your Web pages more interactive, read Special Edition Using JavaScript from Que Publishing. |
→ | O’Reilly and Associates, Inc. has a Web site with great information concerning the history and evolution of JavaScript. You can access it at www.oreillynet.com/pub/a/javascript/2001/04/06/js_history.html. |
JavaScript can be difficult for new programmers to learn. There are several traits to the language that lend to this difficulty, but perhaps the most frustrating for beginners is that JavaScript is case-sensitive. Almost all JavaScript programmers have gone through the pains of pulling their hair out because of a lowercase letter where there should have been an uppercase one, or vice versa. Debugging problems because of wrong case can be tough. Fortunately, Expression Web 2 provides IntelliSense for JavaScript, making it much easier to avoid many of the problems new programmers encounter.
→ | For more information on using IntelliSense, see Chapter 8, “Using Web Page Views,” p. 123. |
→ | For more information on debugging JavaScript code, see the “Lagniappe” section of this chapter. |
JavaScript can be added to a Web page either right within the page’s HTML code or in an external script file with a .js
file extension. To add JavaScript to a Web page, use the <script>
tag. JavaScript code can consist of standalone code sections that are executed as soon as the browser encounters them and JavaScript functions that are executed only when they are explicitly called.
A function is a section of code that performs an action. To run code in a function, you simply use the function’s name. The following code section defines a JavaScript function called writeDateTime
in a Web page. The function is called when the page is loaded by specifying the function name in the onload
event of the <body>
tag.
<html> <head> <script language="javascript" type="text/javascript"> <!-- function writeDateTime() { document.write(Date()); return true; } //--> </script> </head> <body onload="writeDateTime();"> </body> </html>
When this Web page is opened in a Web browser, the current date and time are displayed, as shown in Figure 24.1. This happens because the onload
attribute of the <body>
tag calls the writeDateTime
JavaScript function. We’ll discuss the details of the function later in this chapter.
Notice that the script is surrounded by HTML comment tags, <!--
and //-->
. These are inserted so that browsers that cannot process JavaScript will ignore the script. Modern browsers have no problems processing JavaScript code, but some older browsers do not understand JavaScript. By enclosing the script in HTML comment tags, you ensure that your page will work correctly for everyone viewing it.
JavaScript can also be included in an external file and linked to a Web page with the <script>
tag. The following code calls the same JavaScript function as the previous example, but it uses an external script file:
<html> <head> <script language="javascript" src="jscript.js" type="text/javascript"> </script> </head> <body onload="writeDateTime();"> </body> </html>
The jscript.js
file contains the JavaScript function that is called in the onload
attribute of the <body>
tag. The code inside jscript.js
is as follows:
function writeDateTime() { document.write(Date()); }
Note that the jscript.js
file does not contain any HTML code, including the <script>
tag. It only contains JavaScript code.
There are benefits to including your scripts in separate files. The primary benefit is that it is very easy to reuse the scripts in many files without duplicating the code in each file. It is also extremely easy to change scripts if needed. If you include a script inside HTML files, a change in the script must be made in every HTML file that includes the script. If the script is inside a .js
file, the script only needs to be changed once—in the .js
file. All HTML files that link to that script will then run the updated script automatically.
Be aware that browsers will store script files in the browser’s cache. If a user’s browser does not check for an updated script file when your page is requested and uses the script file in cache instead, unpredictable behavior can occur.
Unfortunately, there isn’t anything you can do to prevent this. The most you can do is include some text on your Web site (perhaps in an FAQ section) that explains how to clear the browser’s cache.
As mentioned earlier, JavaScript can be entered as standalone code instead of being contained inside a function. When JavaScript is entered into a page as standalone code, the code is executed as soon as it is encountered. The following code produces the same output as the code you saw previously, but it does so with a standalone code segment instead of a JavaScript function:
<html> <head> </head> <body> <script language="javascript"> <!-- document.write(Date()); //--> </script> </body> </html>
Notice that in this example, there is no line declaring a JavaScript function. Instead, only the code that was previously inside the writeDateTime
function is included. In the previous example, for the code to execute, you had to call the writeDateTime
function from the onload
attribute of the <body>
tag. In this example, no function call is required because the JavaScript code is not within a function. As you can see, placing JavaScript code inside a function allows you to control when that code is run.
Because JavaScript inside a function does not run until the function is called, the Web browser will not inform you of any errors in that code until you call the function. Therefore, when you are testing pages with JavaScript functions in them, make sure you call all your functions during testing.
Most of the interactivity in Web pages today is accomplished using DHTML. When you write DHTML code, you use scripting (typically JavaScript) to control the CSS attributes of HTML elements on a page. For example, the flyout menus so commonly seen on the Internet these days (see Figure 24.2) are created by causing page elements to appear when a mouse is hovered over a menu item and disappear when the mouse pointer is moved off the menu item. These types of menus are often referred to as DHTML menus because they use DHTML for their functionality.
To script the elements on a Web page, the JavaScript code must have some way to programmatically access those elements. It does this using the Document Object Model, or DOM, for the browser. For the most part, the DOMs for the major browsers are very similar, but that doesn’t necessarily mean that code that works in one will work in another. Even so, with a bit of work, you can write JavaScript code that is compatible with all the major browsers available today.
The W3C has a standard for the DOM, but most Web browsers do not strictly conform to it. Instead, most browsers implement their own DOM that includes specific functionality only for that browser.
At the top of the DOM hierarchy is the window
object. Underneath the window
object, you will find an extensive list of objects—far too many to cover in a single chapter of this book. However, you will learn about some of the commonly used objects in the DOM.
The window
object refers to the browser window itself. It is used to manipulate the browser window and its elements. For example, to change what is displayed in the status bar (the lower portion of the browser window), you would use the status
property of the window
object.
The following code example changes the status bar message:
<html> <head> <script language="javascript" type="text/javascript"> <!-- function changeStatus(msg) { window.status = msg; return true; } //--> </script> </head> <body onload="changeStatus('Welcome!'),"> </body> </html>
When this page is opened in the Web browser, the status bar text will say Welcome!
. Note that when the changeStatus
function is called, the text Welcome!
is passed to it in parentheses. When the function runs, the text passed to it is assigned to the msg
variable, which is then displayed in the status bar.
Using this method of passing a value to a function makes it convenient to reuse the function for other purposes. For example, to display a different message in the status bar of the browser at a different point in the page, you would simply call the changeStatus
function again and pass the text you want to display to it. This function can be made even more robust by saving it as an external .js
file and simply linking that file to each page that needs to use the changeStatus
function.
One of the objects under the window
object in the DOM hierarchy is the document
object. The document
object is one of the most frequently used objects by JavaScript programmers because it provides access to all the elements on a Web page.
In Internet Explorer, the all
collection of the document
object contains a reference to every element on a Web page and is often used by Internet Explorer developers to reference a particular item. For example, consider this <div>
tag:
<div id="border">Web page border goes here.</div>
To get a reference to this <div>
tag, you would simply use the following line of code:
document.all("border")
By appending the ID of the <div>
to the all
collection, this line of code returns a reference to the <div>
with that ID.
This works great in Internet Explorer, but it won’t work in other browsers because only Internet Explorer supports the all
collection of the document
object. Therefore, a better method to get a reference to the <div>
tag is to use the getElementById
method of the document
object. The following code will get a reference to the <div>
tag, and it will work in all modern browsers:
document.getElementById("border")
This code will return a div
element that references the <div>
tag called border
. Once you have that reference, you can then programmatically interact with the <div>
tag, as you will see later.
Firefox actually supports document.all
, but not in the way you might expect. If you use document.all
in a script loaded into Firefox, you’ll see a friendly message notifying you that you’ve used a non-standard syntax and referring you to the document.getElementById
method.
There are many other objects in a browser’s DOM. By reviewing developer information provided by the browser you are targeting, it should be easy for you to take advantage of what the DOM has to offer. The best way for you to start down that road is to write a little code, so let’s write a few sample scripts that implement some real-world scenarios.
Now that you have a general idea of how to write JavaScript code, you are ready to look at a few examples of how you can use JavaScript in your Web pages. In this section, you will learn how to hide and show page elements using JavaScript, how to access elements on a page and read and change their attributes, and how to check information entered into a form before it’s submitted. These three tasks are the most common tasks taken on by JavaScript developers.
The finished pages and files for all these scripts are located in the ExamplesCh24FilesWebsite
folder on the CD accompanying this book.
One of the most common techniques in browser scripting is changing page content based on certain conditions, such as when the mouse pointer passes over a particular graphic. This type of effect is extremely easy to implement with Expression Web 2 behaviors, but you might want to edit the code that Expression Web 2 generates. You also might find that a behavior doesn’t do exactly what you need and decide to implement your own script. In these cases, understanding how this type of effect is achieved with JavaScript is invaluable.
In this example, you will create a Web page with a list of links on the left side. When you pass over a link, text on the Web page will change to indicate the nature of the link you are pointing to. All this will be accomplished using DHTML, which is programmed using JavaScript.
Create a new Web site or open an existing Web site.
Create an empty Web page.
Insert a table with 1 row and 2 columns, no border, and a width of 100%.
Right-click on the left column and select Cell Properties.
Check the Specify Width check box.
Select the In Pixels option and enter 150
for the width.
Click OK.
Save your page.
The left column will contain links to parts of the Web site. When you hover over each link, text describing that link will appear in the right column of the table. To implement this, you will need to insert a div
to hold the text description for each link. When you hover over a link, you will display the div
for that link and hide all the other div
s.
Enter the following text in the left column and press the Enter key after each item:
Home Page
Our Products
About Us
Contact Us
In a real-world Web site, you would link each of these to their respective pages in the Web site; but for now, simply link each one to the page you are currently editing so you will have a hyperlink to work with.
Now you will need to create some <div>
tags to hold the text for each link. To do this, you will use the layers feature in Expression Web 2.
If the Layers task pane is not visible, select Task Panes, Layers to display it.
Add a new layer to the page.
Size and position the layer so it appears in the right column of your table.
Right-click the layer and select Copy.
Right-click the layer again and select Paste.
Right-click the layer and select Paste three more times so there are four total layers—one right on top of the other.
Right-click the first layer in the Layers task pane and select Modify ID.
Change the first layer’s ID to Home
.
Change the second layer’s ID to Products
.
Change the third layer’s ID to About
.
Change the fourth layer’s ID to Contact
.
Right-click the Home layer and select Set Visibility: Hidden.
Repeat step 12 for the remaining layers.
Save the page.
Your page should now look like Figure 24.3.
Expression Web 2 uses absolute positioning for layers. All the layers you inserted are stacked on top of one another. Therefore, any text added to a div
will appear in the same place on the page because each div
sits on its own layer at the same position on the page.
→ | For more information on using layers, see Chapter 25, “Using Layers,” p. 437. |
When you make layers hidden using the task pane, Expression Web 2 simply adds a CSS property to the <div>
tags to make them hidden. That property is the visibility
property. For example, the following <div>
tag is hidden:
<div id="Products" style="visibility: hidden;">I am hidden.</div>
When the Web page containing this <div>
tag is loaded, the div
will be invisible.
When a div
is not absolutely positioned, hiding it using the visibility
property will make it invisible, but the browser will still reserve space for the div
. The result is an empty area where the div
is on the page. To prevent this, use the display
property for a div
that is not absolutely positioned. When the display
property is set to none
, the div
will not be displayed and the browser will close up the space where the div
used to be.
For each layer, enter some text that describes the content for the link. To do this, first click the layer in the Layers task pane, and then click inside the layer. Enter any text you choose for each layer.
When someone visits your Web site, you want the text for the Home layer to be visible right away. If the site visitor then hovers over one of your other links, you want the layer for that link to be displayed. To do that, you will need to enter some code.
Switch to Code View and add the following JavaScript code before the closing </head>
tag:
<script language="javascript" type="text/javascript"> <!-- function hideAllDivs() { document.getElementById('Home').style.visibility = 'hidden'; document.getElementById('Products').style.visibility = 'hidden'; document.getElementById('About').style.visibility = 'hidden'; document.getElementById('Contact').style.visibility = 'hidden'; } function changeVisibility(layer) { document.getElementById(layer).style.visibility = 'visible'; return true; } //--> </script>
→ | For more information on entering code in Code View, see Chapter 8, “Using Web Page Views,” p. 123. |
Two JavaScript functions exist in this code. The first one, hideAllDivs
, sets the visibility
property of each div
to hidden
. Remember that when you set a layer to be invisible, Expression Web 2 sets an inline style by adding a style
attribute to the <div>
tag. The value of that style
attribute is visibility: hidden
. To programmatically set an inline style on an element, you use the style
attribute of the element. In the hideAllDivs
function, you are setting an inline style for each div
, and that inline style sets the visibility
property to hidden
.
The second function, changeVisibility>
, makes whatever layer name is passed to it visible by setting the visibility
property to visible
. For example, to make the Products layer visible, you would call the changeVisibility
function using the following code:
changeVisibility('Products'),
When the changeVisibility
function is called with this line of code, the layer
variable in the function is assigned the value Products
, and the getElementById
function then returns a reference to the Products layer on the page. The style
attribute is then used to set the visibility
property to visible
.
Now you need to add some code that will call these functions at the appropriate times to finish the page. First, you need to make sure the Home layer is visible when the page is first loaded. To do that, call the changeVisibility
function for the Home layer when the page loads.
Make sure you’re still in Code View and edit the <body>
tag of your page so it resembles the following:
<body onload="changeVisibility('Home'),">
The onload
event of the <body>
tag is triggered automatically as soon as the page has finished loading. When an event is triggered, that event is said to have fired. By adding a call to the changeVisibility
function in the onload
event of the <body>
tag, you cause the Home layer to become visible when the onload
event is fired.
The final step is to edit the hyperlinks you created so they cause the correct layers to appear and disappear as the mouse moves over them. To add this functionality, you need two different events: the onmouseover
event and the onmouseout
event. The onmouseover
event is fired when the mouse moves over the element, and the onmouseout
event is fired when the mouse moves off the element.
Locate the <a>
tag for the Products link and edit it so it resembles the following:
<a href="default.htm" onmouseover="hideAllDivs();changeVisibility('Products')," onmouseout="hideAllDivs();changeVisibility('Home'),">
The onmouseover
event first calls the hideAllDivs
function. This causes any visible div
to be hidden in preparation for displaying the Products layer. It then calls the changeVisibility
function and passes Products
to it. This causes the Products layer to become visible. Note that a semicolon appears between the two function calls.
When the mouse is moved off the Products link, the onmouseout
event is fired. This event again calls the hideAllDivs
function, which hides the Products layer. It then calls the changeVisibility
function to make the Home layer visible again because we’re on the home page.
To finish the page, edit the About and Contact hyperlinks just as you did the Products hyperlink. Make sure you pass the correct layer name to the changeVisibility
function in the onmouseover
event. After you edit your hyperlinks, save the page and preview it in your browser to see your layers swapped out as you hover over the hyperlinks.
If the divs
don’t change when you mouse over them, see “Divs
Don’t Change on Rollover” in the “Troubleshooting” section of this chapter.
JavaScript code is often used to access attributes of HTML tags. Using JavaScript, you can read the value of a particular attribute and also change the value of an attribute. Web pages that use image swapping use this technique to change the image file displayed when the mouse hovers over an image. In this section, you will write some JavaScript code to swap an image when your mouse hovers over it.
The HTML <img>
tag has an attribute called src
that specifies the image file to be displayed. By using JavaScript to change the src
attribute of an image tag, you can easily create the effect of swapping one image with another. To do this, you will need to perform two primary tasks: preload the images and write the code to swap the images.
Before you get started, you will need a couple of images to work with. You can use the ewdlogo.jpg
and ewdlogo_over.jpg
images in the ExamplesCh24FilesSwap
folder on the CD accompanying this book, or you can use your own images. Just make sure the images are the same size so the rollover effect will work correctly. Save whatever images you decide to use in the images
folder of your Web site.
Your first step is to add JavaScript code to preload the images that will be swapped. You want to preload the images because if you don’t, when your Web site visitors hover over your original image, they will have to wait for the browser to download the second image before the images are swapped. This delay may take several seconds on a slow Internet connection, and that delay will make your effect seem unprofessional.
Preloading images with JavaScript is an easy task. Open a new page and enter the following JavaScript code before the closing </head>
tag:
<script language="javascript" type="text/javascript"> <!-- grayImg = new Image(); grayImg.src = "images/ewdlogo.jpg"; colorImg = new Image(); colorImg.src = "images/ewdlogo_over.jpg; //--> </script>
This code defines two variables called grayImg>
and colorImg
. It then sets these variables equal to a new Image
object. An Image
object is an object that represents an HTML <img>
tag. You then set the src
attribute of the new Image
object to the image file you want to display for that object. After this code runs, you will have two Image
objects: one for the ewdlogo.jpg
image (the initial image) and one for the ewdlogo_over.jpg
image.
Note that this code does not exist within a function call. That’s because you want this code to run when the page loads. You could place this code within a JavaScript function and call it in the onload
event of the <body>
tag, but doing that would cause the script to run immediately after the page loads. If your Web site visitor were to mouse over the image as soon as the page finishes loading, you wouldn’t get the benefit of preloading the image.
You can also use the Preload Images behavior to preload images. However, because I feel that understanding what goes on when you use that behavior is important, I have included the code necessary to preload images.
As a matter of fact, the Swap Image and Swap Image Restore behaviors can be used to implement the example demonstrated here. However, by learning how the code underlying those behaviors works, you’ll be able to build scripts yourself that don’t lock you into one particular implementation.
The next step is to write a function to swap the images. Because you might want to reuse this function in other Web pages, it makes sense to write it so it isn’t specific to the images you are using in this example. Instead, the function should be written as a generic function that can swap images based on the information passed to it.
Edit your script to include the swapImage
function as follows:
<script language="javascript" type="text/javascript"> <!-- grayImg = new Image(); grayImg.src = "images/ewdlogo.jpg"; colorImg = new Image(); colorImg.src = "images/ewdlogo_over.jpg"; function swapImage(imgID, imgObj) { if (document.images) { document.images[imgID].src = imgObj.src; } } //--> </script>
The swapImage
function takes two parameters: imgID
and imgObj
. The imgID
variable will contain the id
attribute of the image that’s being swapped. This allows you to refer to the correct page element. The imgObj
variable is the object name for the image you want to display in place of the original image. When the function runs, the src
attribute of the original image is changed to the src
attribute for the swapped image. Since the images have been preloaded, the result of this function is that the image instantly changes.
Now the JavaScript code is in place. All that’s left is to insert the original image into a new Web page and then add some JavaScript function calls to the <img>
tag. Insert the ewdlogo.jpg
image onto your page. Using the Quick Tag Editor, edit the <img>
tag so it appears as follows:
<img alt="EWD Logo" id="ewdlogo" src="images/ewdlogo.jpg" width="329" height="247" onmouseover="swapImage('ewdlogo', colorImg);" onmouseout="swapImage('ewdlogo', grayImg);" />
→ | For more information on the Quick Tag Editor, see Chapter 13, “Using the Quick Tag Tools,” p. 223. |
The <img>
tag now contains code for the onmouseover
event that calls the swapImage
function and passes 'ewdlogo'
and colorImg
to it. This tells the JavaScript function you are changing the image for the tag with an id
attribute of ewdlogo
. It also tells the JavaScript function that you want to change the src
attribute of the tag so it’s equal to the src
attribute of the colorImg
object. The src
attribute of the colorImg
object is set when the images are preloaded, so when the mouse hovers over the grayscale picture of the Expression Web 2 graphic, it changes automatically to a color picture right before your eyes. The onmouseout
event calls the swapImage
function again to change the images back. Using this exact same procedure, you are now equipped to write your own JavaScript rollover buttons.
If there is a delay when the images swap, see “Images Don’t Swap Instantly” in the “Troubleshooting” section of this chapter.
JavaScript is also commonly used to validate form fields in Web pages. In this section, you will write JavaScript that will validate an HTML form and make sure that data was entered in each form field. It will also check to ensure that only numeric characters are entered in a particular field and that no more than three digits are entered in an age field.
First, you will need to create an HTML form to be validated by your script:
Create a new page in your Web site.
Insert an Input (Text) form control from the Form Controls section of the Toolbox.
Insert another Input (Text) control on the form under the first one.
Type Enter your name:
above the first text box.
Type Enter your age:
above the second text box.
Double-click the first text box and change the name to txtName
.
Double-click the second text box and change the name to txtAge
.
Insert an Input (Submit) control under the second Input (Text) control.
Save the page.
Your page should now resemble Figure 24.4.
If you’d prefer to use a completed sample instead of entering the code yourself, you can copy the code from the ExamplesCh24Files
folder on the CD that accompanies this book.
Now you will need to enter some JavaScript code to validate the form. Here’s the JavaScript function to validate both form fields:
<script language="javascript" type="text/javascript"> function validateForm(theForm) { var txtName; var txtAge; var nums = '0123456789'; txtName = theForm.elements[0]; txtAge = theForm.elements[1]; if ((txtName.value == '') || (txtAge.value == '')) { alert('Please specify both your name and your age.'), return false; } for (var i = 0; i < txtAge.value.length; i++) { if (nums.indexOf(txtAge.value.charAt(i)) == -1) { alert('You can only specify numeric data for age.'), return false; } else if (txtAge.value.length > 3) { alert('You cannot possibly be that old.'), return false; } } return true; } </script>
Go ahead and add this script to your page just before the closing </head>
tag.
This script is the most complicated yet, but it’s not quite as complex as it appears at first glance. The first three links set up three variables: one for the txtName
form field, one for the txtAge
form field, and one for the numeric characters you will validate the txtAge
field against.
Next, the script sets the txtName
and txtAge
variables equal to their respective form fields. To get a reference to each form field, you use the variable called theForm
. This variable will hold a reference to whatever has been passed into the validateForm
function. As you will see later, a reference to the form itself is passed to this function. The elements
collection contains one object for each form field in the form. The first form field is called elements[0]
, the second elements[1]
, and so on. The first element in your form is the txtName
form field, so the txtName
variable is assigned to theForm.elements[0]
. The txtAge
variable is then assigned to theForm.elements[1]
, the txtAge
form field.
When you have a reference to both the txtName
and txtAge
form fields, you must check to ensure that both contain data. Do this by checking to see whether their value
property is an empty string with the following line of code:
if ((txtName.value == '') || (txtAge.value == ''))
The value
property returns the data entered into the form field. If the value
property returns an empty string, you know the user hasn’t entered any data and you must display an appropriate message using the alert
method. (Notice that to check whether one value is equal to another value in JavaScript, you use double equals signs. The double pipe symbol (||
) is the logical OR
operator in JavaScript.) Therefore, if either txtAge
or txtName
contain no data, validation will fail.
The next validation to perform is checking whether the txtAge
form field contains any non-numeric values. To do this, you use a string variable (nums
) that contains all the valid numerical values. You then check each character in the txtAge
form field against that string variable. Here is the code segment that performs the check:
for (var i = 0; i < txtAge.value.length; i++) { if (nums.indexOf(txtAge.value.charAt(i)) == -1) {
The first line sets up a for
loop. A for
loop runs through a particular code segment repeatedly as long as a particular condition is met. When you define a for
loop, you specify three items that control how the loop is executed: a variable that indicates how many times the loop has run, a condition that must be met for the loop to continue running, and an incrementer for the loop counter that adds 1 to its present value each time the loop runs.
In the loop example, the variable that will indicate how many times the loop has run is called i
, and it is initialized to 0
at the beginning of the loop. The condition is then specified so that as long as i
is less than the length of whatever is entered into the txtAge
form field, the code segment will continue to be executed. Finally, i
is incremented with the i++
statement, which adds 1 to its present value.
The ++
symbol means to increment the value to the left by 1. This syntax is used in many languages other than JavaScript, including C and C++. In fact, C++ got its name from the fact that its developers believed it to be one better than C.
When this code runs, the loop executes once for every character in the txtAge
form field. Each time it runs, it checks a single character in the txtAge
form field (using the charAt
function) to see if it contains any value other than one of the numbers in the nums
variable. It does this using the indexOf
function. The indexOf
function returns the position of one string within another string. If the string is not found, a value of -1
is returned. Each character in the txtAge
form field should be found somewhere within the nums
string variable. If it is not, you know it is not a numeric value and you must display the appropriate message.
The final check determines whether the length of the text entered into the txtAge
form field exceeds three digits. If it does, you must display a message letting the user know he or she has lied about his or her age.
If any of the previous validations fail, you must return a value of false
from the validateForm
function because validation has failed. After a value is returned from a function, processing of that function stops. Therefore, the last line in the function must return a value of true
because you know if you’ve gotten that far, validation has succeeded.
You need to add one final bit of code to make this all work. You need to add a call to the validateForm
function. You do that in the onsubmit
event of the form. Using the Quick Tag Editor, edit the <form>
tag as follows:
<form method="post" onsubmit="return validateForm(this);">
The onsubmit
event fires when the form is submitted. In this event, you call the validateForm
function and pass a reference to the form using the this
keyword. The this
keyword will always contain a reference to the particular element containing it. It is a convenient way to pass a reference to an element of a function. Because you used return
when calling the function, the return
statement inside the validateForm
function will return either true
or false
. If the value is false
, the form will not be submitted. If the value is true
, the form will submit as usual.
Save the page now and preview it in your browser. Submit the form without entering any data and examine the result. Next, enter your name in both fields and note that you are told that the txtAge
form field can only contain numeric data. Finally, enter an age of 1000
and try to submit the form.
This is a simple validation script. In a real-world environment, you would want your validation script to be much more robust than this. However, this script gives you a solid foundation on the methods used when validating forms.
When I roll the mouse over my links, the text doesn’t change.
The most common cause of this is a typographical error in your code. Look in the status bar of the browser and make sure that an error doesn’t appear in your script. If it does, carefully review the code you entered to make sure you haven’t made a mistake.
This can also be caused by having scripting turned off in your browser. To check this in Internet Explorer, select Tools, Internet Options and click the Security tab. Select the appropriate zone (select Internet if using a URL with dots in it and Intranet if using a URL without dots) and click the Custom button. Make sure the Enabled option is selected for Active Scripting. At the time of this writing, other browser companies are preparing to release major updates, so check for scripting in other browsers. Consult the documentation provided with the browser.
I’ve entered all the code, including the preloading code, but my rollover image doesn’t swap instantly. Instead, there is a delay while the second image loads.
Internet Explorer can be configured so it checks the Web server each time a file is requested to see if a newer version is on the server. This check can cause a delay in the display of rollover images.
To correct this, select Tools, Internet Options. Make sure the General tab is selected and click the Settings button. In the Check for Newer Versions of Stored Pages section, choose the Automatically option and click OK.
So far, the assumption has been that all the JavaScript you’ve entered will run without problems. As long as you’ve entered it correctly, it will, but that’s because I’ve already debugged it for you! In the real world, code almost never runs successfully on the first try. Sometimes you get lucky and your code runs without debugging, but almost all code requires some level of debugging to get the desired results.
There are two types of problems you can encounter with code: syntax errors and logic errors. Syntax errors are often the easiest errors to resolve. For example, the following line of code will generate an error:
document.Write('Welcome!'),
Remember, JavaScript is case-sensitive. The write
method does not start with an uppercase "W"
, so when this line executes, it will generate an error.
Logic errors are much harder to track down. A logic error occurs when code is written so that it runs without syntax errors, but the code produces undesired results. Logic errors are hard to track down because when an error occurs, it will often point to a part of code that is nowhere near where the actual error is located. Suppose, for example, you have a function that returns a specific numeric value and that function contains a logic error. You have code in a completely different area that relies on the number returned from the first function. When the code runs and an error occurs, the error message might point to the section of code using the number returned from the function, not the function itself.
There are many approaches to debugging JavaScript code. One is to use the JavaScript alert
method to display messages at certain places in the code. For example, if a function returns a specific numeric value, you can place an alert
method at the end of the function call and display the value the function returns, as shown in the following example:
function debugTest() { var i; i = document.getElementById('txtYears').value; alert(i); return i; }
When this function runs, an alert dialog box will display, indicating the value of i
. An even more effective way to debug client script is to use the free Visual Web Developer 2008 Express Edition from Microsoft. For more information about debugging client script using Visual Web Developer 2008 Express Edition, read my book The Microsoft Expression Web Developer’s Guide to ASP.NET 3.5 from Que Publishing.