22. Client Scripting

A History of Browser Scripting

Early sites consisted of many of the same page elements we use today: forms, images, hyperlinks, and static text. They also consisted of small applications called applets that ran inside the 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 site developers were not Java developers, so it needed to find a way to allow non-Java developers to interact with Java applets on 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, one of the common uses for JavaScript at the time is still a common use of script 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 (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.

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 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.


Image Note

Around this same time, web developers began writing scripts to check for Netscape browsers by seeing whether the browser identified itself as “Mozilla,” an identifier Netscape Navigator used at the time. As browsers added functionality, they all began to identify themselves as “Mozilla Compatible” so scripts would work successfully. Even today, you will see all browsers identified as Mozilla if you review server logs for your site.


Image For more information on DHTML, see “The Document Object Model” section in this chapter, p. 363.

The majority of client-side scripting on the Internet today is used to script DHTML effects in pages. Although Internet Explorer still supports VBScript as a scripting language, the vast majority of web developers use JavaScript and not VBScript because it works in all major browsers. For that reason, this chapter sticks to a discussion of JavaScript.

Expression Web provides tools such as behaviors and interactive buttons that can generate JavaScript code for you. However, if you want to add more robust scripts to your page or modify the scripts Expression Web generates—or if the scripts Expression Web 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 pages more interactive, read Special Edition Using JavaScript from Que Publishing.

• O’Reilly and Associates, Inc., has a 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 Basics

JavaScript can be difficult for new programmers to learn. The language has several traits 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 provides IntelliSense for JavaScript, making it much easier to avoid many of the problems new programmers encounter.

Image For more information on using IntelliSense, see Chapter 4, “Using Page Views.”

Image For more information on debugging JavaScript code, see the “Debugging” section of this chapter, p. 377.

Adding JavaScript to a Page

JavaScript can be added to a 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 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 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 page is opened in a web browser, the current date and time are displayed, as shown in Figure 22.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.

Image

Figure 22.1. The output of the writeDateTime() JavaScript function.

Linking to an External Script File

JavaScript can also be included in an external file and linked to a 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, not even the <script> tag. It contains only JavaScript code.

Including your scripts in separate files has benefits. The primary benefit is that reusing the scripts in many files without duplicating the code in each file is simple. You also can easily 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.


Image Caution

Be aware that browsers 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 a simple solution to this, but one thing you can do is include some text on your site (perhaps in an FAQ section) that explains how to clear the browser’s cache.


Adding Inline JavaScript

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 this example does not contain a 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.


Image Tip

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, be sure you call all your functions during testing. One nice way of doing this is to create a test page that calls all of your functions.


The Document Object Model

A lot of the interactivity in 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, many of the flyout menus so commonly seen on the Internet these days (see Figure 22.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.

Image

Figure 22.2. Flyout menus, such as this one on the Microsoft site, are created with JavaScript code.

To script the elements on a page, the JavaScript code must have some way to programmatically access those elements. It does this using the Document Object Model (DOM) for the browser. For the most part, the DOMs for the major browsers are 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.


Image Note

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 learn about some of the commonly used objects in the DOM.

The window Object

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.

The document Object

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 page.

In Internet Explorer, the all collection of the document object contains a reference to every element on a page and is often used by Internet Explorer developers to reference a particular item. For example, consider this <div> tag:

<div id="border">page border goes here.</div>


Image Note

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 nonstandard syntax and referring you to the document.getElementById method.


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 gets a reference to the <div> tag, and it works in all modern browsers:

document.getElementById("border")


Image Note

The finished pages and files for all these scripts can be downloaded from the website for this book at www.informit.com/.


This code returns a div element that references the <div> tag called border. After you have that reference, you can then programmatically interact with the <div> tag, as you will see later.

Many other objects exist in a browser’s DOM. By reviewing developer information provided by the browser you are targeting, you should be able to easily 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.

Writing Simple Scripts

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 pages. In this section, you 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.

Showing and Hiding Page Elements

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 easy to implement with Expression Web Behaviors, but you might want to edit the code that Expression Web 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 create a page with a list of links on the left side. When you pass over a link, text on the page changes to indicate the nature of the link you are pointing to. All this is accomplished using DHTML, which is programmed using JavaScript. Do the following:

1. Create a new site or open an existing site.

2. Create an empty page.

3. Insert a table with one row, two columns, no border, and a width of 100%.

4. Right-click the left column and select Cell Properties.

5. Check the Specify Width check box.

6. Select the In Pixels option and enter 150 for the width.

7. Click OK.

8. Save your page.

The left column contains links to parts of the site. When you hover over each link, text describing that link appears in the right column of the table. To implement this, you need to insert a div to hold the text description for each link. When you hover over a link, you display the div for that link and hide all the other divs.

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 site, you would link each of these to its respective pages in the 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 need to create some <div> tags to hold the text for each link. To do this, you use the layers feature in Expression Web.


Image Tip

Expression Web 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.


1. If the Layers panel is not visible, select Panels, Layers to display it.

2. Add a new layer to the page.

3. Size and position the layer so it appears in the right column of your table.

4. Right-click the layer and select Copy.

5. Right-click the layer again and select Paste.

6. Right-click the layer and select Paste two more times so there are four total layers—one right on top of the other.

7. Right-click the first layer in the Layers panel and select Modify ID.

8. Change the first layer’s ID to Home.

9. Change the second layer’s ID to Products.

10. Change the third layer’s ID to About.

11. Change the fourth layer’s ID to Contact.

12. Right-click the Home layer and select Set Visibility: Hidden.

13. Repeat step 12 for the remaining layers.

14. Save the page.

Your page should now look like Figure 22.3.

Image

Figure 22.3. The page is now ready for you to add some code.

Image For more information on using layers, see Chapter 23, “Using Layers.”


Image Tip

When a div is not absolutely positioned, hiding it using the visibility property makes it invisible, but the browser still reserves 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 is not displayed and the browser closes up the space where the div used to be.


When you make layers hidden using the panel, Expression Web 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 page containing this <div> tag is loaded, the div will be invisible.

For each layer, enter some text that describes the content for the link. To do this, first click the layer in the Layers panel and then click inside the layer. Enter any text you choose for each layer. You might want to change the visibility to Visible temporarily while you enter the text so you can see what you’re typing.

When someone visits your 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 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>

Image For more information on entering code in Code View, see Chapter 4, “Using Page Views.”

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 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.

To finish the page, you need to add some code that calls these functions at the appropriate times. First, you need to ensure 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 create hyperlinks so that clicking the text you entered in the left cell causes the correct layers to appear and disappear as the mouse moves over them. To add this functionality, you need two 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.

Select Our Products in the left cell, and then right-click and select Hyperlink. Select default.html, and then click OK. Now switch to Source view and 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, add a hyperlink to the About and Contact text just as you did with Products, and then edit the hyperlinks as you just did with 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.

Image For more information on add-ins in Expression Web, see the online Chapter 36, Expression Web 4 Add-in Basics.”


Image Tip

You can also add the Mark of the Web to your page to allow scripts to run from a disk location. Expression Web comes with an add-in that makes adding the Mark of the Web easy. Select Insert, HTML, Mark of the Web to add it.


Accessing and Changing Attributes

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. 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 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 need to perform two primary tasks: preload the images and write the code to swap the images.

Before you get started, you need a couple of images to work with. You can use the ewdlogo.jpg and ewdlogo_over.jpg available on this book’s website at www.quepublishing.com, or you can use your own images. Just make sure the images are the same size so the rollover effect works correctly. Save whatever images you decide to use in the images folder of your site.


Image Tip

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.


Preloading Images

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 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 can 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 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.

Writing a Function to Swap Images

The next step is to write a function to swap the images. Because you might want to reuse this function in other 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 contains 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. Because the images have been preloaded, the result of this function is that the image instantly changes.

Adding the Images

Now the JavaScript code is in place. All that’s left is to insert the original image onto the 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);" />

Image For more information on the Quick Tag Editor, see Chapter 8, “Using the Quick Tag Tools.”

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 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.

Form Field Validation

JavaScript is also commonly used to validate form fields in pages. In this section, you write JavaScript that validates an HTML form and ensures that data was entered in each form field. It also checks 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.

Creating the Form to Validate

First, you need to create an HTML form to be validated by your script:

1. Create a new page in your site.

2. Insert an Input (Text) form control from the Form Controls section of the Toolbox.

3. Insert another Input (Text) control on the form under the first one.

4. Type Enter your name: above the first text box.

5. Type Enter your age: above the second text box.

6. Double-click the first text box and change the name to txtName.

7. Double-click the second text box and change the name to txtAge.

8. Insert an Input (Submit) control under the second Input (Text) control.

9. Save the page.


Image Note

If you’d prefer to use a completed sample instead of entering the code yourself, you can download the code from the website for this book at www.informit.com.


Your page should now resemble Figure 22.4.

Image

Figure 22.4. The finished HTML form that will be validated with JavaScript.

Adding the JavaScript Validation Function

Now you 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 holds 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.

Validating the Form Fields

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.


Image Note

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.


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 indicates 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.

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 whether 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 has lied about his 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.

Adding the Call to the JavaScript Function

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 always contains 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 returns 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.

Debugging

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 generates 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 generates 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 often points 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 displays, indicating the value of i. An even more effective way to debug client script is to use the script debugging functionality included in Internet Explorer 8. Select Tools, Developer Tools, and then click the Script tab. For more information on debugging with Developer Tools in Internet Explorer 8, visit msdn.microsoft.com/en-us/library/dd565625%28VS.85%29.aspx.

Easier Scripting with jQuery

As you might have noticed, using JavaScript to manipulate the browser’s DOM is sometimes a little tricky. Different browsers work a little bit differently, so you have to take that into account when writing your JavaScript. It can also be frustrating when you have to write several lines of code to access a particular element on a page. Most developers have experienced this frustration, and thankfully, there is a solution: the jQuery library.

The jQuery library consists of a JavaScript file that can be linked to as an external script file. jQuery adds powerful methods for accessing and manipulating DOM elements, and when you use jQuery, you don’t have to worry about browser interoperability. jQuery takes care of that for you.


Image Note

You can download jQuery from www.jquery.com. There are two versions: a developer version, and a production version. The production version is compressed so that it’s smaller and will take less time to download. Unless you plan on making changes to the jQuery library (or debug the library), I recommend you get the production version.


After you’ve downloaded the jQuery library, you can link the script to a page just like you did earlier in this chapter. After you do that, you’ll immediately have access to all the power of jQuery. Even better, as long as you have Service Pack 2 or later installed, you’ll have IntelliSense for jQuery inside of Expression Web 4.

Coverage of JavaScript programming using jQuery is outside of the scope of this book, but there are great tutorials and other information available at www.jquery.com.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.183.150