Copyright Ó 2000, Bits & Bytes Programming, Inc. ALL RIGHTS RESERVED

Table of Contents

Using scripting languages with Web pages. 3

Why data verification is an issue with Web applications. 3

Two main scripting languages. 4

Working with JavaScript 5

Level of browser support 5

Browsers that do not support JavaScript or have disabled scripting. 6

Hiding scripts from non–supporting browsers. 6

More about JavaScript 7

Syntax. 7

Objects used in JavaScript 7

Placement on a Web page. 7

Use of Functions. 8

JavaScript References. 9

Reference Manuals. 9

JavaScript sample code. 10

JavaScript Editing Sample. 11

Edits performed at the browser 12

Editing Process. 12

Editing Techniques. 14

Browser detection. 14

Netscape FormChek.js functions. 14

Message display. 14

Editing Techniques. 15

Select/Focus. 15

Conversion to Uppercase. 16

Multiple input buttons. 16

document.write to generate HTML. 16

Code for the sample form.. 17

Code review - HTML. 23

Section 19. 24

Section 20 – 28. 24

Section 29 – 31. 24

Section 32. 25

Code review – JavaScript 26

Section 1. 26

Section 2. 27

Section 3. 27

Section 4. 27

Section 5. 28

Section 6. 28

Section 7. 28

Section 8. 28

Sections 9 – 13. 28

Code review – JavaScript (continued) 29

Section 14. 29

Section 15. 29

Section 16. 29

Section 17. 30

Section 18. 30


Using scripting languages with Web pages

For most Web query applications, you can use Net.Data, CGI or Java functions and language constructs to prompt for and run a query. Each of those techniques provides a number of techniques you can use to retrieve data and format it using HTML.

However, if you will be creating Web data entry applications, you will probably want to add editing capabilities to your Web pages so that you can verify that required data is entered and that the data is valid.

Why data verification is an issue with Web applications

The main reason why data verification is an issue with Web applications is because of the response time if you need to transmit data to the Web server to be edited. In a LAN environment, the response time issue is not much of a problem, regardless of your application type (5250 emulation, client/server, intranet).

However, if you are designing and implementing applications to be used over the Internet, you need to carefully consider when and where editing will be done. If you simply send all of the data entered on a form to the Web server, you potentially have one or more additional "round–trips" from the browser to the Web server and back to edit data. Given the lack of response time predictability for Internet applications, editing at the Web server may not be the best approach.

Two other techniques are available for editing form data:

The level of Java support in the various browsers and versions of browsers varies greatly. It can be very difficult to create an applet that will work correctly in the different browsers and versions.

Applets can become rather large. For example, applets that use the AS/400 Toolbox for Java may be several hundred kilobytes in size. On dial–up connections, users may not be willing to wait for the applet to download.

Two main scripting languages

There are two main scripting languages used in browser applications:

Ÿ        VBScript — invented by Microsoft, this is a subset of the Visual Basic programming language. VBScript is natively supported in Microsoft Internet Explorer. However, you need to acquire a chargeable plug–in to run VBScript in Netscape Navigator. VBScript is only practical in an intranet environment where you mandate the use of Microsoft Internet Explorer.

Ÿ        JavaScript — although invented by Netscape Communications Corp. and implemented in the Netscape Navigator series of browsers, JavaScript is also supported in Microsoft Internet Explorer. Because JavaScript is natively supported by the two leading browsers, this it your best choice for a scripting language.

You may also see JavaScript referred to as ECMA–262 (European Computer Manufacturers Association standard 262). This is a standard for the implementation of JavaScript and is supported by both Netscape Communications Corp. and Microsoft.


Working with JavaScript

Although it may seem like extra work to create JavaScript functions and send those functions as source code to the browser along with the HTML, the advantage is that your application does not require a trip to the Web server just to perform simple field validations.

When you use JavaScript code in your Web applications, the work flow is like this:

  1. Your Web server transmits the Web page that includes the JavaScript code and HTML.
  2. The connection between the browser and your Web server is broken.
  3. The user can spend as much time as needed making entries on the form.
  4. When the user clicks a submit button to send the form to the Web server, the JavaScript editing code is invoked.
  5. If there are any errors in the data the user entered, the JavaScript code displays message boxes in the browser. You can include any text you want in the message box to describe the error condition to the user.
  6. The user makes changes to the invalid data and clicks submit again. The edits are performed again.
  7. When all of the edits are passed, the browser sends the form data to the Web server.

Steps 3–6 are performed at the browser, with no interaction with the Web server. For most types of data, it should be possible to verify that the entries are valid before sending the data to the server (for example, dates). Other data can be verified but may still be invalid (for example, you may require the user to enter a name, but you cannot verify that they enter a valid name).

Level of browser support

JavaScript is supported by recent generations of Web browsers. Netscape introduced support for JavaScript in the Netscape Navigator version 2.0 browser. Microsoft supports JavaScript in their Internet Explorer version 3.01 browser.

Browsers that do not support JavaScript or have disabled scripting

One of the on–going problems of designing Web applications is that you need to consider the level of support available to your intended audience in their browser. For example, if you absolutely must allow potential users access to your Web pages and discover that they use browsers that do not support JavaScript, then you may need to provide editing capabilities in your server–side code in addition to or instead of in JavaScript that is sent to the browser.

However, you may find that your application is sufficiently complex that you do not want to replicate the client–side edits on the server also. In that case, you might mandate that users have a JavaScript enabled browser available and that they have not disabled scripting in their user options.

In your HTML code, you can use the <NOSCRIPT> tag to indicate what should happen if your Web page is sent to a browser that does not support JavaScript. For example:

<script language=JavaScript>

   (some JavaScript code here)

</script>

 

<noscript>

   Your browser must support JavaScript to access this site.

</noscript>

 

Hiding scripts from non–supporting browsers

You will usually see examples of "hiding" JavaScript code in JavaScript documentation. This refers to a technique you can use to prevent a browser that does not support scripting from displaying the script code in the browser (the browser simply considers the JavaScript code as HTML comments).

The technique is to put the JavaScript code in HTML comments:

   <script language=JavaScript>

   <!--- Hide JavaScript from browser

         (some JavaScript code here)

   //  End hiding JavaScript -->

   </script>

 

The last comment line is a JavaScript comment (//) and an HTML comment end (-->). The effect is that the browser sees all of the code between the <script> and </script> tags as comments which are not displayed in the browser.

 


More about JavaScript

The most important thing to realize about JavaScript is that it is not Java. Although there are some similarities in the way Java and JavaScript code is written, the underlying concepts and architecture of each language are completely different.

Syntax

JavaScript syntax is similar to Java syntax:

Objects used in JavaScript

JavaScript includes a number of predefined objects that it can work on. Some of the objects are:

Those objects make it possible for JavaScript to dynamically alter the presentation in the browser at run–time. For example, you can use JavaScript code to open another browser window to display another document.

Placement on a Web page

Scripting code sent to a browser is usually located inside the <head> </head> tag pair. By placing the scripting code inside that tag pair, the functions in the script are available to all forms defined on the Web page.

The script code itself is contained in the <script> </script> tag pair. You can optionally specify the scripting language and version of JavaScript to use:

<script language=JavaScript>

<script language=JavaScript1.2>

You can also specify the name of a JavaScript source file that is to be included:

<script src=FormChek.js>

 

There are two advantages to using the src method:

Use of Functions

JavaScript code is typically written in functions. You can pass parameters to the function and return a value from the function:

function checkForm(formToCheck) {

 

   var validForm = true;

   (...some edits...)

 

   if (!validForm) {

         return false;

   }

}

 

The sample code shown above shows how to pass a value to a function (formToCheck) and how to return a value from a function (return false;).

You invoke a JavaScript function from a Web page by using event handlers that are defined for objects used on your Web page. For example, button objects have an onClick event handler:

   <input type=”button”

          value="Submit Form"

          onClick=”checkForm(myForm)”>

The sample code shown above is used to invoke the checkForm function when the Submit Form button is clicked.

Variables that are defined as HTML fields on your form are accessible within your JavaScript code. For example, if you have the following field defined:

   <input type=”text”

          name=”FORM_SHIPTO_NAME”

          size=”40”

          maxlength=”40”>

 

then you can access the variable FORM_SHIPTO_NAME in your JavaScript code.


JavaScript References

Some of the best available reference information about JavaScript is available at Netscape's developer's sites:

http://developer.netscape.com/docs/manuals/index.html

 

Select JavaScript on the page that is displayed.

Netscape also has many freely available samples of JavaScript code at the following site:

http://developer.netscape.com/docs/examples/index.html

Reference Manuals

You can view the JavaScript Reference and JavaScript Guide at Netscape's site. However, you may find it very useful to download those manuals so they are more readily available. You can download the manuals in either HTML or PDF format (you need the Adobe Acrobat Reader to view and print the PDF format).

Another good reference book to get is Pure JavaScript (Gilliam, Ting, Wyke), Sams Publihsing, ISBN 0-672-31547-5.


JavaScript sample code

If you are new to JavaScript, you should plan to spend some time downloading and working with the sample code Netscape has at their site.

You should particularly get the FormChek.js file from the Netscape JavaScript samples Web page (the link is identified as Form Validation with JavaScript 1.0). That file includes the check functions shown above in addition to many other editing functions you can use. Some of the commonly used functions are:

Each of the check functions displays an error message if the value that is checked is not valid.


JavaScript Editing Sample

Figure 1 shows a sample HTML form in the browser. This is a typical data-entry type form, with several fields that can be edited in the browser before sending the form to the server for processing.

JAVASCR001

Figure 1: The sample form that uses JavaScript for field edits.


Edits performed at the browser

The following edits are performed at the browser for the sample form:

Although there may be other types of edits that you want to perform for this type of data, the sample code for this form will show you how to get started.

Editing Process

The sample form lets you edit the field values two different ways. You select an editing technique by clicking the different “check fields” buttons:

 

JAVASCR002

Figure 2: The alert box that is displayed when checking all fields at once.

JAVASCR003

Figure 3: A sample edit for a single field at a time.

Note: the error field on the form (below the “Check fields – all at once” button) shown in Figure 3 is only used when the form is displayed in Microsoft Internet Explorer. The error field is actually an HTML <input> field type with a “READONLY” property set. Netscape Navigator browsers through all of the 4.x versions do not support the “READONLY” property. If you use the <input> field in Netscape Navigator, the user would be able to key over the error message.


Editing Techniques

The sample code demonstrates several techniques that you might want to use with your forms.

Browser detection

Because the <input> field type with a “READONLY” property is only supported in the Microsoft Internet Explorer series of browsers, the JavaScript code uses browser detection to determine the user agent (browser type). After determining the browser type, the code sets the value of a JavaScript variable that will be tested later.

Netscape FormChek.js functions

The Netscape FormChek.js functions mentioned earlier in this manual are included in the form. By including that script file, you have access to a library of JavaScript functions. Rather than have to write the low-level editing code, you can simply call the functions in the script file and use the return values to control how your edit process works.

Message display

The sample form uses three different techniques to display error messages:

You can use any combination of these message display techniques with your forms.


Editing Techniques

The sample form also demonstrates some other editing techniques that you may find useful.

Select/Focus

This capability is similar to the AS/400 DDS DSPATR(RI PC) (Display Attribute, Reverse Image and Position Cursor).

Figure 4 shows a sample of the select/focus methods being used to help edit a field on the form.

JAVASCR004

Figure 4: The sample form, showing the select/focus methods on the ZIP code field.

Conversion to Uppercase

On the sample form, the city name and state code are automatically converted to all uppercase characters when the user tabs out of the fields. Although not strictly required for the city name, the edit function for the state code in FormChek.js requires the state code to be in uppercase, otherwise, it rejects the state code.

Multiple input buttons

Because the purpose of the form is to demonstrate different editing techniques, there are two different input buttons that work with the text fields on the form. When you use two or more input buttons in the same form, you need to process the input buttons with JavaScript. Both of the buttons call the CheckFields function.

document.write to generate HTML

Because the READONLY input field is only valid in Microsoft Internet Explorer, the form uses conditional HTML code generation to output the HTML for the field as the form is loaded. The conditional code generation uses the value of the browser name from the browser detection code described earlier.


Code for the sample form

 

<html>
<head>
       <title>JavaScript Edits</title>
      
<!—SECTION 1
à      <script      src="FormChek.js">
             </script>
      
<!—SECTION 2
à     <script language="JavaScript">


             //--SECTION 3-------------------------------------------------
             // code to execute when page is loaded
             // retrieves userAgent to determine browser type,
             // if Microsoft Internet Explorer, set variable browserType
             //------------------------------------------------------------
             var browserType;

             if (navigator.userAgent.indexOf('MSIE') >= 0) {
                    browserType = "MSIE";
             }



             //--SECTION 4-------------------------------------------------
             // CheckFields - validate all input fields
             //------------------------------------------------------------
             function CheckFields(checkType) {

                    var validData   = true;
         //SECTION 5
                    var msgAddress1 = "Address line 1 must be entered.\n";
                    var msgCity     = "City must be entered.\n";
                    var msgData     = "The following errors were detected:\n\n";
                    var msgDay      = "A valid day must be entered.\n";
                    var msgMonth    = "A valid month must be entered.\n";
                    var msgShipTo   = "Ship-to name must be entered.\n";
                    var msgState    = "A valid State code must be entered.\n";
                    var msgYear     = "A valid year must be entered.\n";
                    var msgZip      = "A valid ZIP code must be entered.\n";

         //SECTION 6
                    ClearErrorMsg();

         //SECTION 7
                    with (document.frmCustomer) {

                           //--SECTION 8------------------------------------------
                           // check for ship-to name entered
                           //-----------------------------------------------------
                           if (isWhitespace(txtShipToName.value)) {
                                 validData = false;

                                 SetFocus(txtShipToName);
                                 msgData = SetErrorMsg(msgData, msgShipTo);

                                 if (checkType != "all") {return;}
                           }

                           //--SECTION 9------------------------------------------
                           // check for address line 1 entered
                           //-----------------------------------------------------
                           if (isWhitespace(txtAddress1.value)) {
                                 validData = false;

                                 SetFocus(txtAddress1);
                                 msgData = SetErrorMsg(msgData, msgAddress1);

                                 if (checkType != "all") {return;}
                           }

                           //--SECTION 10-----------------------------------------
                           // check for city entered
                           //-----------------------------------------------------
                           if (isWhitespace(txtCity.value)) {
                                 validData = false;

                                 SetFocus(txtCity);
                                 msgData = SetErrorMsg(msgData, msgCity);

                                 if (checkType != "all") {return;}
                           }

                           //--SECTION 11-----------------------------------------
                           // check for valid U.S. State code
                           //-----------------------------------------------------
                           if (isWhitespace(txtState.value)) {
                                 validData  = false;

                                 SetFocus(txtState);
                                 msgData = SetErrorMsg(msgData, msgState);

                                 if (checkType != "all") {return;}
                           }

                           else {
                                 if (!isStateCode(txtState.value)) {
                                        validData  = false;

                                        SetFocus(txtState);
                                        msgData = SetErrorMsg(msgData, msgState);

                                        if (checkType != "all") {return;}
                                 }
                           }

                           //--SECTION 12-----------------------------------------
                           // check for valid U.S. ZIP code
                           //-----------------------------------------------------
                           if (isWhitespace(txtZip.value)) {
                                 validData = false;
                                 SetFocus(txtZip);
                                 msgData = SetErrorMsg(msgData, msgZip);

                                 if (checkType != "all") {return;}
                           }

                           else {
                                 if (!isZIPCode(txtZip.value)) {
                                        validData = false;

                                        SetFocus(txtZip);
                                        msgData = SetErrorMsg(msgData, msgZip);

                                        if (checkType != "all") {return;}
                                 }
                           }

                           //--SECTION 13------------------------------------------
                           // check for valid Requested delivery date
                           //-----------------------------------------------------
                           if (!isMonth(txtDateMonth.value)) {
                                 validData  = false;

                                 SetFocus(txtDateMonth);
                                 msgData = SetErrorMsg(msgData, msgMonth);

                                 if (checkType != "all") {return;}
                           }
                           if (!isDay(txtDateDay.value)) {
                                 validData  = false;

                                 SetFocus(txtDateDay);
                                 msgData = SetErrorMsg(msgData, msgDay);

                                 if (checkType != "all") {return;}
                           }

                           if (!isYear(txtDateYear.value)) {
                                 validData  = false;

                                 SetFocus(txtDateYear);
                                 msgData = SetErrorMsg(msgData, msgYear);

                                 if (checkType != "all") {return;}
                           }

                           //--SECTION 14------------------------------------------
                           // format error message, include all errors
                           //-----------------------------------------------------
                           if (!validData) {

                                 ClearErrorMsg();
                                 alert(msgData);
                           }
                    }     
             }     


             //--SECTION 15------------------------------------------------
             // ClearErrorMsg - clear the window status and
             //   MSIE readonly error message field
             //------------------------------------------------------------
             function ClearErrorMsg() {

                    window.status = "";

                    if (browserType == "MSIE") {
                           document.frmCustomer.txtErrorMsg.value = "";
                    }
             }



             //--SECTION 16-------------------------------------------------
             // SetErrorMsg - performs the following for an error message:
             //   - set the window status to display the message
             //   - set the readonly text box to display the message (MSIE)
             //   - add the message to the cumulative error message, which
             //     is displayed in an alert
             //
             //  msgData  - cumulative error message
             //  errorMsg - error message for field in error
             //------------------------------------------------------------           
             function SetErrorMsg(msgData,
                                 errorMsg) {

                    window.status = errorMsg;

                    if (browserType == "MSIE") {
                           document.frmCustomer.txtErrorMsg.value = errorMsg;
                    }

                    return msgData + errorMsg;
             }


             //--SECTION 17------------------------------------------------
             // SetFocus - select and set the focus to the specified item
             //------------------------------------------------------------
             function SetFocus(focusItem) {

                    focusItem.select();
                    focusItem.focus();

             }

<!—SECTION 18
à

       </script> 
</head>

<body>

<!—SECTION 19
à

<form  name="frmCustomer"
       method="post"> 

       <center>
             <h1>
                    JavaScript Edits - Individual or All fields
             </h1>


       <table border="1"
             bgcolor="lightblue"
             cellpadding="1"
             cellspacing="1">

             <tr>
                    <td    colspan="2"
                           align="center">
                           <b>Sample Customer Data Form</b>
                    </td>
             </tr>              

<!-- Ship-to name -->
             <tr>
                    <td>
                           <font  size="-2">
                                 Ship-to name
                           </font>
                    </td>

<!—SECTION 20
à    <td> 
                           <input name="txtShipToName"
                                 type="text"
                                 size="40"
                                 maxlength="40">
                    </td>
             </tr>

<!-- Address line 1 -->
             <tr>
                    <td>
                           <font  size="-2">
                                 Address line 1
                           </font>
                    </td>

<!—SECTION 21
à    <td>
                           <input name="txtAddress1"
                                 type="text"
                                 size="30"
                                 maxlength="30">
                    </td>
             </tr>

<!-- Address line 2 -->
             <tr>
                    <td>
                           <font  size="-2">
                                 Address line 2
                           </font>
                    </td>

<!—SECTION 22
à
                    <td>
                           <input name="txtAddress2"
                                 type="text"
                                 size="30"
                                 maxlength="30">
                    </td>
             </tr>

<!-- City / State / Zip -->
             <tr>
                    <td>
                           <font  size="-2">
                                 City, State ZIP
                           </font>
                    </td>

<!—SECTION 23
à
                    <td>
                           <input name="txtCity"
                                 type="text"
                                 size="30"
                                 maxlength="30"
                                 value=""
                                 onBlur="this.value = this.value.toUpperCase()">

                           &nbsp;

<!—SECTION 24
à
                           <input name="txtState"
                                 type="text"
                                 size="2"
                                 maxlength="2"
                                 value=""
                                 onBlur="this.value = this.value.toUpperCase()">

                           &nbsp;

<!—SECTION 25
à
                           <input name="txtZip"
                                 type="text"
                                 size="5"
                                 maxlength="5">
                    </td>
             </tr>

<!-- Delivery date -->
             <tr>
                    <td>
                           <font  size="-2">
                                 Requested delivery date<br>(MM/DD/YYYY)
                           </font>
                    </td>

<!—SECTION 26
à
                    <td>
                           <input name="txtDateMonth"
                                 type="text"
                                 size="2"
                                 maxlength="2">

<!—SECTION 27
à
                           /
                          
                           <input name="txtDateDay"
                                 type="text"
                                 size="2"
                                 maxLength="2">

                           /
                          
<!—SECTION 28
à
                           <input name="txtDateYear"
                                 type="text"
                                 size="4"
                                 maxlength="4">
                    </td>
             </tr>

<!-- Submit buttons -->
             <tr    bgcolor="navy">
                    <td    colspan="2"
                           align="center">

<!—SECTION 29
à
                           <input type="button"
                                 value="Check fields - all at once"
                                 onClick="CheckFields('all')">

                           &nbsp;

<!—SECTION 30
à
                           <input type="button"
                                 value="Check fields - individually"
                                 onClick="CheckFields('single')">

                           &nbsp;

<!—SECTION 31
à
                           <input type="reset"
                                 value="Clear fields">
                    </td>
             </tr>

             <script language="JavaScript">
                    //-------------------------------------------------------------
                    // if browser is Microsoft Internet Explorer, output
                    // table row for input with "readonly" attribute.
                    // This is used to display an error message.
                    //-------------------------------------------------------------
<!—SECTION 32
à
                    if (browserType == "MSIE") {

                           document.write('<tr>');
                           document.write('<td colspan="2">');
                           document.write('<input type="text"');
                           document.write('       name="txtErrorMsg"');
                           document.write('       value=""');
                           document.write('       maxlength="65"');
                           document.write('       size="65"');
                           document.write('       readonly>');
                           document.write('</td>');
                           document.write('</tr>');
                    }
             </script>
       </table>
      
       </center>
<!—SECTION 33
à
</form>
</body>
</html>



 

Code review - HTML

To understand how the JavaScript editing code works, you first need to understand the HTML used on the form. For review, the form is shown in Figure 5.

The section numbers refer to the numbers shown in the sample code on the previous pages.

JAVASCR001

Figure 5: The sample form.

Section 19

The actual HTML to display the form starts at this point. In addition to the <body> tag, the <form> tag marks the beginning of the form. All of the HTML input fields and buttons are included, through the closing </form> tag (see Section 33).

The most important feature of this form tag is the name: frmCustomer. When you use JavaScript editing code, you need to use that name to identify the items on the form that you are working with.

Section 20 – 28

The code in these sections defines the label and input field for each of the items on the form. The name property of each input field is important, since you will use that name when editing the field.

The input fields at sections 23 and 24 use the onBlur event handler to convert the value entered into the field to uppercase characters when the user tabs out of or otherwise exits the field.

Section 29 – 31

The code in these sections is used to create the input buttons. Sections 29 and 30 are button type objects, and use the onClick event handler to invoke the CheckFields function that is defined in Section 4. Note that each button passes a different parameter value to the CheckFields function.

Section 31 defines an HTML reset button. When the button is clicked, all of the fields on the input form are cleared. There is no option to clear just a subset of the fields, so you need to consider carefully if you should include a reset button on your forms.

Section 32

Section 32 is used to conditionally generate HTML for the READONLY input field, if the browser is a version of Microsoft Internet Explorer. The value of the browserType variable is set in Section 3, which is executed when the form is first loaded.

If the browserType is MSIE (a value that is set in Section 3), the document.write statements are executed. Those statements add an additional table row to the form, with the input field embedded within the table row. If the document.write statements are not executed, the table simply ends at the row with the input buttons.


 

Code review – JavaScript

Most of the JavaScript code on the Web page is located in the <head> section of the page. When you place JavaScript code in the <head> section of a form, it is available from any point within the form.

Section 1

The code at Section 1 is used to include the FormChek.js file into the JavaScript for the Web page. Although you can copy the actual source code in FromChek.js into the source code for the form, you will probably prefer to use the technique shown here, which uses the src property to identify the name of the file to be included.


Here are some reasons why you might prefer to use the src= technique:

Note that this section ends with the closing </script> tag. Although not strictly required, since you will be using additional script immediately following the opening tag, you may find it useful to use separate <script> </script> blocks for different purposes. There is no limit to the number of script blocks you can have in a Web page source file.

Section 2

This section starts the script source code for the editing functions. Notice that the scripting language is specified on the tag. Although not strictly necessary, since the browsers assume JavaScript by default, you may find it helpful to specify the scripting language explicitly.

Section 3

This section of code is executed immediately when the page is loaded. The code declares the global variable browserType which is tested in Sections 15 and 32.

For the purposes of this Web page, we want to know if the browser in use is Microsoft Internet Explorer, since an MSIE specific feature will be used (the READONLY property of an input field, see Section 32). The navigator.userAgent property returns a string that identifies the type of browser being used. The indexOf method is used to determine if the character string MSIE occurs within the string returned. If MSIE is in the string, the value of the index will be greater than or equal to 0 (the first position in the string is position 0), and the value of the browserType variable is set to MSIE.

Note: you can view the entire userAgent string by including the following line immediately after the opening <script> tag in Section 2:

document.write(navigator.userAgent);

Section 4

The function line in this section is the beginning of the CheckFields function. This function takes one input parameter (checkType). The function is invoked when one of the buttons is clicked (see Sections 29 and 30).


Section 5

This section is used to declare the variables used in the function. The variables are local to the function (their values cannot be used outside of the function).

Section 6

This line of code calls the ClearErrorMsg function, defined in Section 15.

Section 7

The with block is used to provide a “shortcut” method for referring to HTML objects on the form. To understand why this is useful, look at the editing code in Section 8, where the value of the txtShipToName field is being checked to determine if it is “whitespace” (blank):

If (isWhitespace(txtShipToName.value)) {

If the with block is not used, you would need to write the line in Section 8 like this:

If (isWhitespace(document.frmCustomer.txtShipToName.value)) {

Also, you would need to write all other lines of code that use HTML objects like that (for example, in Sections 9 –13).

Another advantage to using the with block is that if you change the name of the HTML form (in Section 19), you only need to change the with line.

Section 8

The code in this section is used to edit the txtShipToName input field.

Sections 9 – 13

The code in these sections is similar to the code in Section 8, in that the value of a field on the form is tested.

Code review – JavaScript (continued)

Section 14

The code in this section tests the value of the validData variable. When the function started, the value of validData was initialized to true, since the assumption is that all fields will be valid (see Section 5). If any of the fields on the form are invalid, the value of validData is set to false, within each field edit (see Sections 8 – 13).

The line reading

If (!validData) {

is read as “if not validData”, which is the case if any of the fields are in error. The code inside this if condition first clears all error messages, then displays the alert box with the msgData string that was built up in the editing sections (8 – 13).

Section 15

This section defines the ClearErrorMsg function, which is used to clear the two locations on the form where an error message might be displayed:

Section 16

This section defines the SetErrorMsg function, which is used to build up the msgData error message string. When there are any errors, the message string is displayed in the alert box, if the check all fields option was selected. (See Figure 2 for a sample of the alert box with a complete error message string.)

There are two parameters passed to the function:

The function performs the following functions:

The new value of msgData is assigned to the msgData variable in each of the editing sections (8 – 13), so the value is built up as each edit is performed.

Section 17

This section defines the SetFocus function, which is used to perform the DSPATR(RI PC) equivalent for a field in error (the effect can be most clearly seen on an invalid ZIP code field, as shown in Figure 4.)

The function takes one parameter, focusItem, which is the name of the input field that is in error (see Sections 8 – 13 where the SetFocus function is invoked).

The select() method is used to select all of the characters in the input field.

The focus() method is used to set the focus (the cursor) to the beginning of the input field.

Section 18

The closing </script> and </head> tags mark the end of the script and the HTML header section.

Copyright Ó 2000, Bits & Bytes Programming, Inc. ALL RIGHTS RESERVED