
As I promised, this month I'll be taking a look at dynamic HTML, or DHTML. Dynamic HTML is not a technology unto itself, but rather it is a term for a collection of Web-oriented technologies: HTML 4.0, cascading style sheets, browser scripting, and the document object model (DOM). DHTML adds a crucial element missing in today's Web browsers: dynamic functionality. This dynamic functionality manifests as (but is not limited to) visual manipulation. More important, DHTML lets us add interactivity to our Web sites that rivals what can be done with non-Web programming environments such as Visual Basic, C++, and Java. In the examples I'll develop in this column and the next one, I'll create an HTML form page that provides user feedback and is more interactive. I'll use DHTML to make sure the user fills in the data properly; if the user doesn't complete some part of the form with proper information, I'll pop up a dialog with a friendly message and prompt the user to complete it correctly.
Because our focus isn't on making our Web pages pretty (that's what designers are for), I will focus on browser scripting and the document object model in this column. My primary interest is in how we can improve our Web-database applications.
Adding dynamic properties in HTML documents to Web pages was possible (in a limited sense) before DHTML. Developers relied on clever HTML tricks combined with server-side scripts to generate and display altered HTML on the Web browser. Not only were these hacks and server-side scripts cumbersome, but they also required the Web server to do some processing, which meant that the lag time for the display of this "dynamic" content was high and very noticeable to the user. DHTML operates entirely on the Web browser, so there is no perceptible delay in the dynamic display, and the server is not bothered to shift around some HTML when, for example, the browser has to load new menu bars when a user navigates a new section of your Web site (so that the current section the user is in is highlighted in the new menu bar) or during HTML form data checking to ensure the user has complete all fields correctly.
Before I get to the example, let's look at the four technologies that DHTML comprises: DOM, HTML 4.0, cascading style sheets (CSSs), and browser scripting.
DOM. The document object model isn't a technology in the same sense that the other three are, but it's the plumbing that lets these three interact with each other. Some refer to DOM as the glue that holds these three Web components together. Simply put, DOM allows access to the HTML elements on a page. It creates a simple object model in which you can reference elements in an HTML document directly. The hierarchical model allows access to all the objects on a page via the main object, aptly named "document." We reference subobjects using a simple dot notation. For example, if we have a form tag named "frm" in an HTML document, we use "document.frm" to refer to that form tag. In our form area, we would have a number of form elements, such as text fields or buttons that we can refer to by the name we've given them. So a button named "send" contained in our form can be referenced like this: document.frm.send. Furthermore, we can get the value property we gave the button by including this in our HTML document: document.frm.send.value.
The DOM provides a platform-independent interface to HTML documents. You can use this hierarchical model to change the content of an HTML document as well as the structure. With the addition of cascading style sheets, the DOM also lets you manipulate the style of a document. You should note at this point that the DOMs for Netscape's browser and Microsoft's browser are different. While it's beyond our discussion here to go into these differences, be aware that they exist and that you will need to design around them until a formal specification is created and implemented in both products.
HTML 4.0. The specification for HTML 4.0 was finalized in late 1997 and includes many improvements to the base HTML standard. Scrollable tables, large tables, better support for printing tables, and other enhancements make HTML easier to use. Of direct relevance to the topic of this column, HTML 4.0 also includes a new attribute for input tags to validate the data the user enters in form fields.
In addition, HTML 4.0 includes features to make forms better. The most interesting is the accesskey attribute for forms, which allows keyboard shortcuts to form fields. This means that users can jump directly to a particular form field using a keyboard shortcut (such as using Alt+F in Windows to jump to the "File" menu in office applications). The ability to have buttons other than submit and reset also means that you have more flexibility in the functionality of your forms.
Cascading style sheets. Style sheets allow precise layout and formatting of HTML elements that increases the flexibility in the design of Web pages while making it easier to create a motif for a site that you can easily follow and incorporate into a range of HTML documents. Style sheets can specify fonts, including type size and color. You can used them to position HTML elements with precision. You can place an HTML element at an absolute location or a location relative to other HTML elements. This ability to have so much control over the position gives the developer ultimate flexibility in the look of the HTML page. In addition, you can use style sheets as templates filling different content in at the appropriate locations in the design layout. For example, a style sheet for your Web site can include standardized color schemes, fonts, and images. You would use this style sheet repeatedly in different pages on your site by simply including a reference to the style sheet's location in each HTML document. Each document that referenced the style sheet would display each page according to the style sheet's specifications. There is a new version of CSSs in the works due out later this year.
Browser scripting. Browser scripting, also known as client-side scripting, has been a part of Netscape's browser for some time (if you think in terms of Web time) as JavaScript. Microsoft followed suit with support of a JavaScript-like language called JScript, then added VBScript to its browser. Browser scripting is basically a lightweight programming language built into a Web browser. This ability to add programming into the client lets us do virtually anything we can dream up--within the limits of the browser, of course. People have been using browser scripting to make Web pages with those annoying scrolling banners in the status bar or in a text field. I'll use browser scripting to do the data validation in the examples (coming up in a moment). The programmer has access to the HTML elements on the page, as well as some of the browser's built-in functionality to load Web pages or access browser plug-ins. Currently, there are two browser scripting languages: JavaScript and VBScript.
The first example shows you how to use browser scripting to perform data validation in an HTML form page. Data validation is simply the affirmation that the data collected and passed through a system matches a certain criterion specified by the developer that can manifest as a constraint at the database level or as a check on a user form. Every database application has some level of data validation. In my examples, I'll implement data validation at the user level (in this case, a Web browser).
Most of today's Web-database applications perform data validation at the Web server tier. When a user submits some data via a Web form, the target Web server-based script (whether it is a CGI, ASP, Cold Fusion, or other type of script) checks to make sure the user entered data properly. If the user enters data improperly or fails to enter some data, the Web server-based script prints an error message and directs the user back to the form page. The inherent drawback to using server-based script validation is that it uses the Web server's resources. This may not seem to present any problems if the number of hits on your Web server is relatively low; however, users will be users, and they will not always complete forms properly. You can alleviate some of the load on your Web server by using browser scripting to move the data validation process to the Web browser. Doing this also speeds the user's interaction with your site because the user doesn't need to wait on your Web server-based script to first verify the form submission and then process the information.
Let's begin our example with the basics of a Web form. Figure 1 shows our form for collecting user comments. It has three fields: two input tags of type text for the user's name and email address and a textarea tag for getting the user's comments. Finally, we have two buttons, one for submitting the form and one to reset the form data. Listing 1
shows the HTML source code for the form. The page uses a table to align the HTML elements properly. If you look closely at the code, you'll see I labeled the form elements on the page, a necessary step if I want to reference them later. Also notice that I named the form tag "UserComment." In addition, I gave the form a target Web server script to run to save the user's comments--to a database, of course!
<HTML> <HEAD> <TITLE>User Comments</TITLE> </HEAD> <H3>Please enter in your comments for our Web site below!</H3> <FORM NAME= "UserComment" ACTION="http:// sunsite.unc.edu/cgi-bin/mail" METHOD="POST"> <TABLE BORDER=0 CELLSPACING=10> <TR><TD> Full Name: <BR> <INPUT TYPE = "TEXT" NAME="username"> </TD></TR> <TR><TD> Email Address: <BR> <INPUT TYPE = "TEXT" NAME = "email"> </TD></TR> <TR><TD> Comments about our Web site: <BR> <TEXTAREA ROWS = "5" COLS = "30" NAME = "comment" WRAP=ON> </TEXTAREA> </TD></TR> <TR><TD> <INPUT TYPE = "SUBMIT" VALUE = "Submit"> <INPUT TYPE = "RESET" VALUE = "Reset"> </TD></TR> </TABLE> </FORM> </BODY> </HTML>
Listing 1.Basic HMTL form.
Now that we have our basic form in Listing 1, let's add some error checking and data validation. The first thing I do is to make sure that the user enters some data in all three input fields (name, email, and comment). I put this JavaScript code in the head tag of our HTML document. While I could put this JavaScript code anywhere in the document, it is best to put script code in the head, ensuring that the script code is parsed and loaded before the rest of the HTML page. I also surrounded the script code with the standard HTML comment tag so it's ignored by browsers that don't support JavaScript. I have to let the browser know that I'm using JavaScript as our script language using the <SCRIPT LANGUAGE = "Javascript"> tag.
Listing 2 shows the updated form. As you can see, I added the necessary JavaScript to validate the form data. (I also included brief explanations of the code in the comments.) I have created only one new function, called checkFields. We trigger this function in the form tag in the HTML by adding the onSubmit = "return checkFields(this)". The onSubmit keyword prompts the Web browser to execute whatever is specified, and uses the returned value of what's executed (in this case, the checkFields function) to decide whether the form data should be sent to the ACTION specified in the same tag. Hence the need for the return before the function name. The checkFields function returns true if the form data passed all the data validation rules, false if it failed any of the checks. Figure 2 shows the alert dialog generated if the user does not enter a valid email address.
<HTML>
<HEAD>
<TITLE>User Comments</TITLE>
<SCRIPT LANGUAGE = "JavaScript">
<!--
function checkFields(form) {
var FormOK = false;
/* Check the User name field first make
sure it's not empty. If it is, display an alert.
FormOK remains at false, sending the user back
to the form. */
if (form.username.value == "") {
alert("Please enter your name!");
}
/* Next, check the email address. Make sure it's
got a @ and . in it. If not, display an alert.
The Javascript function indexOf returns the
location in a string of the parameter.
Here, the parameters are @ and . -if they aren't present
in the string, it returns a -1 value.
The || is a simple AND keyword. */
else if (form.email.value.indexOf("@") == -1 ||
form.email.value.indexOf(".") == -1) {
alert("Please enter a valid email address!");
}
/* Last, check to make sure something was entered
into the comments TextArea. */
else if (form.comment.value == "") {
alert("Please enter your comments!");
}
/* If all of the tests were passed, change the
value of FormOK to true. */
else {
FormOK= true;
}
/* Finally, return the value of the FormOK variable.
It will let the browser know it's acceptable
to send the form data to the ACTION specified in the
FORM tag. */
return FormOK;
}
//-->
</SCRIPT>
</HEAD>
<H3>Please enter in your comments for our Web site below!</H3>
<FORM NAME= "UserComment" ACTION="http://
www.yourwww.com/cgi-bin/comments.cgi" METHOD ="POST"
onSubmit ="return checkFields(this);">
<TABLE BORDER=0 CELLSPACING=10>
<TR><TD>
Full Name:
<BR>
<INPUT TYPE = "TEXT" NAME="username">
</TD></TR>
<TR><TD>
Email Address:
<BR>
<INPUT TYPE = "TEXT" NAME = "email">
</TD></TR>
<TR><TD>
Comments about our Web site:
<BR>
<TEXTAREA ROWS = "5" COLS = "30"
NAME = "comment" WRAP=ON>
</TEXTAREA>
</TD></TR>
<TR><TD>
<INPUT TYPE = "SUBMIT" VALUE = "Submit">
<INPUT TYPE = "RESET" VALUE = "Reset">
</TD></TR>
</TABLE>
</FORM>
</BODY>
</HTML>
Listing 2. Updated HTML form with Data Validation.
While browser scripting is a great addition to the Web developer's toolbox, you must use it with caution because there are certain incompatibilities between the Netscape and Microsoft browsers' versions of JavaScript. These incompatibilities mean that you have to be careful not to use functions or objects that are not supported by both browsers, or you risk your scripts not working on one of the browsers. If you decide to do your browser scripting using VBScript, be aware that only users with Microsoft's Internet Explorer will be able to use it.
And remember, you can do more with browser scripting then the simple data validation we've done here. For example if you want to limit the user's input, you can write a short JavaScript function to count the number of words a user enters in a text field. You can also check to make sure that a ZIP code contains only numbers. Furthermore, you could use scripting, for example, for creating a calculator application, starting a plug-in, or manipulating a Java applet in a Web page. Do a Web search to find sites that have ready-to-use scripts and tutorials on how to do more advanced scripting. In my next column, I'll continue the examination of DHTML and use it to implement a help system for our form using style sheets.
Pratik R. Patel is a researcher in the UNC-Chapel Hill Medical Informatics research program and is developing
Web-based systems for healthcare. You can reach him via email at prpatel@sunsite.unc.edu.