Dynamic Web Forms Professional Projects [1 ed.] 9781931841139, 1931841136

A step-by-step guide to help you learn lively Web form development bymeans of JavaScript, PHP, MySQL, Apache, and more.

310 41 3MB

English Pages 537 Year 2002

Report DMCA / Copyright

DOWNLOAD PDF FILE

Recommend Papers

Dynamic Web Forms Professional Projects [1 ed.]
 9781931841139, 1931841136

  • 0 0 0
  • Like this paper and download? You can publish your own PDF file online for free in a few minutes! Sign Up
File loading please wait...
Citation preview

D y n a m ic W e b For m s Pr of e ssion a l Pr oj e ct s by Dan Ran som

ISBN: 1931841136

Pr em ier Pr ess © 2002 (755 pages) A st ep- by - st ep guide t o help y ou lear n liv ely Web for m dev elopm ent by m ean s of Jav aScr ipt , PHP, My SQL, Apache, and m or e.

T a b le o f Co n t e n t s Dy nam ic Web For m s Pr ofessional Pr oj ect s I nt r oduct ion Pa r t I - D y n a m ic W e b For m s Ov e r v ie w

Ch apt er 1

- I nt r oduct ion t o Dy nam ic Web For m s

Ch apt er 2

- Dy n am ic Web For m Concept s and Consider at ions

Ch apt er 3

- HTML Form s

Ch apt er 4

- Jav aScr ipt and Web For m s

Ch apt er 5

- Ser v er - Side Scr ipt ing and Relat ional Dat abases

Ch apt er 6

- Modular I nt er face Design

P a r t I I - Pr oj e ct 1 : Cr e a t in g M e m be r sh ip For m s

Ch apt er 7

- Pr oj ect 1 Pr epar at ion: Designing for Modular izat ion

Ch apt er 8

- Cr eat ing t he For m s

Ch apt er 9

- Com plet ing t he Mem ber ship I nt er face

Pa r t I I I - Pr oj e ct 2 : Cr e a t in g Ca t a log For m s

Ch apt er 1 0 - User I nt er face Design Ch apt er 1 1 - Designing a User I nt er face Ch apt er 1 2 - Cr eat ing t he Online Cat alog I nt er face Ch apt er 1 3 - Com plet ing t he Cat alog I nt er face P a r t I V - Pr oj e ct 3 : Cr e a t in g On lin e I n for m a t ion Sy st e m s

Ch apt er 1 4 - Funct ional Design Ch apt er 1 5 - Designing a Funct ional I nt er face Ch apt er 1 6 - Cr eat ing t he Online I nfor m at ion Sy st em I t self Ch apt er 1 7 - Com plet ing t he I nfor m at ion Sy st em I nt er face Pa r t V - Be y on d t h e La b

Ch apt er 1 8 - XML and XFor m s Ch apt er 1 9 - Em bedded Web For m Technologies Pa r t V I - Ap p e n d ice s

Appen dix A - HTML For m Elem ent s Refer ence Appen dix B - Recom m ended Nam ing Conv ent ions Appendix C - Resour ces for Web For m s I n dex List of Figur es List of Tables List of Sidebar s

Dynamic Web Forms Professional Projects Dan Ransom © 2002 by Premier Press, Inc. All rights reserved. No part of this book may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system

without written permission from Premier Press, except for the inclusion of brief quotations in a review. The Premier Press logo, top edge printing, and related trade dress are trademarks of Premier Press, Inc. and may not be used without written permission. All other trademarks are the property of their respective owners. Important: Premier Press cannot provide software support. Please contact the appropriate software manufacturer’s technical support line or Web site for assistance. Premier Press and the author have attempted throughout this book to distinguish proprietary trademarks from descriptive terms by following the capitalization style used by the manufacturer. Information contained in this book has been obtained by Premier Press from sources believed to be reliable. However, because of the possibility of human or mechanical error by our sources, Premier Press, or others, the Publisher does not guarantee the accuracy, adequacy, or completeness of any information and is not responsible for any errors or omissions or the results obtained from use of such information. Readers should be particularly aware of the fact that the Internet is an ever-changing entity. Some facts may have changed since this book went to press. ISBN: 1-931841-13-6 Library of Congress Catalog Card Number: 2001098163 Printed in the United States of America 02 03 04 05 RI 10 9 8 7 6 5 4 3 2 1 Publisher: Stacy L. Hiquet Marketing Manager: Heather Buzzingham Managing Editor: Sandy Doell Acquisitions Editor: Kevin Harreld Project Editor: Estelle Manticas Editorial Assistant: Margaret Bauer Technical Reviewer: Michelle Jones Copy Editor: Hilary Powers Interior Layout: Shawn Morningstar Cover Design: Mike Tanamachi Indexer: Sharon Shock Proofreader: Lorraine Gunter Dedication This one’s just for me Acknowledgments I’d like to take this opportunity to thank everyone who made this book possible. Thanks to Kim and Stacy; they took a chance and gave me a shot. Thanks also to Estelle, Kevin, and all the editors who had the patience to deal with my not-so-minor annoyances. A very special thanks to my friends and family who had to deal with a lot of unreturned phone calls and missed gatherings while I spent nights and weekends over a keyboard to put this together. Finally, thanks to God and everyone else who never quite gets thanked enough—you know who you are. About the Author Dan Ransom is a rarity among Web developers: a generalist. He has a solid grounding and experience in graphic design, programming, user interface design, Website architecture, and code optimization. Surprisingly, despite all this, he can still put together a bit of code that doesn’t look like it was based on an Escher drawing. Currently Dan works as an Internet consultant for Scribner and Associates (www.scribnerconsulting.com). When he’s not redesigning user interfaces Dan dabbles in Flash and Java, and he plays Unreal Tournament at least twice a week (for stress). Dan lives outside Sacramento, California and plays the harmonica, badly.

Introduction This book is intended to take a developer to the next step in Web interface design. JavaScript programmers will learn how to leverage their skills to create effective serverside scripts, server-side developers will learn how to extend their knowledge to the client environment, and everyone will learn the concepts behind creating modular, usable, and functional form-based user interfaces.

What’s in this Book? Creating dynamic Web forms is more than simply slapping some code onto an HTML form. This book provides a hands-on approach to learning dynamic Web form development using popular freeware technologies such as JavaScript, PHP, MySQL, and Apache. I have included many examples of ready-to-use code that can be applied to most any Website. Part I of the book covers the basic principles of how the code is created and reviews the technologies needed to start creating dynamic Web forms. The majority of this book—Parts II, III, and IV—consists of three professional projects. These projects are based on the types of real-life interfaces wherein dynamic Web forms can be of benefit. These projects move from simple dynamic membership forms to a multi-functional information systems interface. Along the way you’ll learn more about each of the technologies involved and the specifics of how they can be applied to Web forms. While the server-side code used for the three projects is based on the combination of PHP and MySQL, the focus is less on the specifics of code and more on how the functionality is achieved. I’ve included information on how these methods can be applied using other relational databases or server-side scripts. Developers familiar with JSP, ASP, or ColdFusion will not only come away with an understanding of the basics of PHP, but will be able to apply many of the same methods and techniques to their preferred development environment. Part V includes two chapters that offer information on other dynamic Web form technologies. Chapter 18 includes a comprehensive overview of XForms, the W3C specification that has the potential to utterly change the way Web interfaces are created. The time for XForms has not yet come, but with this introduction you should be prepared for when it does. Chapter 19 compares and reviews some of the embedded technologies: Flash, ActiveX, and Java Applets.

Who Should Read this Book? This book is intended for the intermediate to advanced Web developer. You should have a grounding in some type of Web scripting language, either client- or server-side. Experience with relational databases will help, but is not required. The projects in this book primarily use JavaScript and PHP. Knowledge of one or both of these languages will allow you to bypass much of the introductory chapters and go directly to the projects. Developers familiar with other scripting languages, such as PerlScript or VBScript, should be able to easily use these skills to adapt the projects to their preferred technology. A solid grasp of HTML is required for all readers.

How to Use this Book Because this book is intended for different types of Web developers, there are numerous ways that it can be used. The majority of readers will benefit by following along with the book through each project step-by-step. This will give you the most comprehensive coverage of all the topics. Some developers however will be more interested in a specific

application of dynamic Web forms and may skip to the project that interests them the most. Still others will want the book mostly for the ready-to-use code examples. In this case, the projects serve more as a guidebook to how the code can be implemented rather than as a learning tool. Finally, some developers may want to use this book as a handy informational resource. This books gathers together information on a wide variety of topics relating to Web interfaces, and some developers may wish to give it a quick review then bookmark the sections most likely to be needed in the future. The following conventions are used in this book: Note Notes give additional information that may be of interest, but is not required to accomplish the task at hand. Caution Cautions are used to alert you to the potential hazards the may result if a task is performed incorrectly.

New Term Definition Terms that may be unfamiliar to you or that may have multiple meanings are noted and defined as part of the text.

Find It Online These messages direct you to Web sites that contain additional information, related material, or valuable resources. Because of the ever changing nature of the Web it is to be expected that some of these links could change or disappear altogether. What’s on the Web Site? This book includes an accompanying Web site located at http://www.premierpressbooks.com. Here you will find the project files and much of the sample code. Whenever source code is displayed for a file located on the Web site, the following notation is used: filename.html

Part I:

Dynamic Web Forms Overview

Chapter List Chapter Chapter Chapter Chapter Chapter Chapter

1: 2: 3: 4: 5: 6:

Chapter 1:

Introduction to Dynamic Web Forms Dynamic Web Form Concepts and Considerations HTML Forms JavaScript and Web Forms Server-Side Scripting and Relational Databases Modular Interface Design

Introduction to Dynamic Web Forms

If you’ve picked up this book, then you probably already have an idea what dynamic Web forms are. They allow a Web site to interact with its visitors, not simply in a static, predefined way, but dynamically. These dynamic Web form elements are presented to the user in some fashion based on information gathered by the Web server, previous interaction with the user, or the specific capabilities and preferences defined by the browser. This chapter covers the basics of what dynamic Web forms are all about and defines the major terms that will be used throughout the book.

Web Forms Web forms have been around for a long time. Unlike other Web technologies such as tables, layers, or style sheets, forms benefited from the fact that every browser manufacturer and Web developer saw the advantage of using forms on the Web. Only the very first Web browsers did not include some form-based functionality, and today you would be hard-pressed to find any of these archaic browsers still in use. This universality extends to how Web forms are implemented. With very few exceptions, all of the basic form elements can be added to a Web page using a standard set of browserindependent HTML. To create a Web form using HTML, you define each form device, called a form element. Together these elements allow a visitor to enter text, choose an option from a number of selections, or upload a file. Gathering direct user input in this manner allows a site to interact with the user in a way not possible using simple hypertext links. How Are Web Forms Used? Simply put, Web forms are used anywhere that the Web site or the user would benefit from an exchange of information. The user benefits because the information exchanged most often allows the site to provide customized service, content, or access that would not otherwise be available. The Web site in turn benefits from the information itself, both directly and indirectly. Direct benefits might include an increase in product sales; indirect benefits might involve an increase in returning visitors or improved marketing information. Most Web sites contain some type of Web form. From the ubiquitous search box to the pop-up survey, Web forms are as common on the Web as their paper forebears are in the physical world. In fact, in many cases Web forms are replacing or supplementing their paper counterparts. You can now use Web forms to file your taxes, apply for a loan, or get an insurance quote. This book presents three typical uses for Web forms: membership forms allow a Web site to gather information about visitors to the site; catalog forms allow online retailers to present a digital storefront where visitors can order products online; information systems forms allow Web sites to disseminate large amounts of information to the general public. Along the way, you will learn the basics for creating search forms, online community forms, and secure forms for maintaining a database of information. How Do Web Forms Work? Chapter 3, “HTML Forms,” and Chapter 5, “Server-side Scripting and Relational Databases,” cover the specifics of how Web forms function, but for now you can understand forms like this: Forms are added to a Web page using HTML. The user interacts with the form elements through a browser, entering data and making selections. The form is sent, or posted, to the specific Web page that was defined by the form. The form information is then processed by an application or script on the server. Finally, a page is returned to the user.

What Tools You Will Need to Create Web Forms Creating Web forms requires a number of applications and tools, but I’m happy to say that versions of most of these can be found as freeware. You should be familiar enough with HTML to know what you need to do to create Web pages, and if you don’t have one

you will need to acquire an HTML editor. Some of these editors will create Web pages for you using a WYSIWYG (What You See Is What You Get) interface. However, I don’t recommend using a WYSIWYG HTML editor to create Web forms. Even the best of these products produce unwanted HTML code or limit the developer to a predefined set of options based on the wizards built into the application. Instead, you should use a textbased HTML editor such as HomeSite or HoTMetaL. Of course, these programs are just glorified text editors that provide color-coded HTML and useful shortcuts. In a pinch you could use any text editor, including Notepad, emacs, or even vi. Any HTML editor will also allow you to create the script files (JavaScript and PHP) used in this book. To capture form input, however, you will need to set up a Web server. Many of the latest operating systems—including Windows 2000, MacOS X, and most Linux flavors—provide a Web server. If you don’t have a Web server you should be able to find a version of Apache, a freeware Web server, that will work on your system. For the purposes of creating and testing the project files it will not be necessary to attach the server to a domain name or IP address. If you need information about how to publish the files on the Web, contact the network administrator or your local Internet Service Provider—that information is outside the scope of this book, and varies a lot depending on the location of the site. Find It Online You can find download and installation information for the Apache Web server at http://www.apache.org. The projects in this book make use of a relational database system called MySQL. As an alternative you could use virtually any SQL-based database that can be accessed by PHP. Chapter 5 describes how you can acquire MySQL and how you can modify the project files presented in the rest of the book for use with alternative databases. If your database is on a different computer from the one with the Web server, you will need to establish a connection. Depending on the server-database combination, this can mean creating a connection string, a Web access account, or an ODBC (Open Database Connectivity) record. Some additional project-specific applications and files will be required. You’ll find download and installation instructions for each of these at the point where they’re needed.

What You Need to Know to Create Web Forms If you don’t know HTML, take some time to pick up a solid grounding before you start this book, or you aren’t likely to get much out of it—I’ve written on the assumption that you already know the basics of HTML and the Internet. What this book will do is get you up to speed with Web scripting and form application processes. First, you will need to know the specifics of how Web forms are presented in HTML. You need to know what attributes are available for each form tag and how other HTML elements, such as CSS styles and table structures, affect Web forms. This will allow you to present your visitors with a uniform and functional form no matter what browser they use. Next, you will need to understand how to process form data using server-side scripts. This will allow you to validate the form data, make any necessary formatting changes, and store the information in a database. While it is possible to use Web forms with client-side scripting exclusively, the processing power of the browser is limited and leaving out the server prohibits interaction with a database. Finally, you will need to know the basics of how to communicate with a database. This will allow form data to be stored permanently.

What Are Dynamic Web Pages? There is often confusion when developers talk about dynamic Web pages. As a simple definition, dynamic Web pages are Web pages that provide content or presentation

elements that have not been explicitly set. For example, a Web page that contains only HTML cannot be dynamic, because both the content and presentation have been predefined by the code on the page. On the other hand, a Web page that includes a JavaScript function that presents a message to the user when a button is clicked is dynamic because the message may or may not appear, depending on what the user decides to do about the button. Server-side technologies can also create dynamic pages. Microsoft’s Web site, for example, provides different pages to the user depending on which browser he or she is using. It is important to understand that while all dynamic pages include some client scripting element or server-side processing, not all pages that include JavaScript or are generated by server-side applications are dynamic. Both client and server-side scripts can be used to generate a page that says “Hi Mom!” to every visitor, but this isn’t a dynamic page. Only Web pages that have some conditional element can be considered dynamic. Note Don’t confuse dynamic Web pages with pages created using dynamic HTML (DHTML). DHTML is a catch-all term that refers to a combination of client-side technologies, usually involving JavaScript and layers, that change the content or presentation of a Web page after it has been loaded into a browser. DHTML Web pages are all dynamic, but not all dynamic Web pages use DHTML. Server-Based Dynamic Pages Server-based dynamic pages rely on scripts or applications on the server to generate conditional content. Originally, servers were limited to using CGI technology to create this functionality. Modern developers, however, have many more choices available, including PHP, ASP, JSP, and ColdFusion. Chapter 5 describes these server-side technologies and how they can be applied to Web forms, but the inherent benefits and difficulties are the same no matter which server-side processing method you choose.

The Benefits of Server-Based Processing Server-side scripting allows a developer to take advantage of the processing power of the Web server. Most server-side technologies have far more raw data processing functionality than client-side scripts. In addition, the server itself is likely to be faster and more powerful than the machine used by the average Web surfer. This increased processing power means that server-based dynamic Web pages can be based on more complex criteria or present a larger amount of potential content. Server-side processing is also the only way for information to be stored or retrieved from a database. Data can be better organized and more permanently stored in a file system or a relational database than is possible using client-side scripts alone. The advantage of database connectivity is magnified for larger sites that have more than a handful of pages. As the page count increases the maintenance costs go up; organizing information in a database can help reduce these maintenance costs. Finally, server-side processing is browser-independent. Regardless of how the file is generated, Web servers still send simple HTML to the browser. The fact that the end product is always in this defined standard allows the developer of a server-based dynamic page to avoid the traps and tribulations that most browser-based projects encounter. Instead, the developer can concentrate on the dynamic data itself.

Difficulties Associated with Server-Based Processing Server-based processing isn’t a bed of roses, however; it has a number of drawbacks. First, the process that the server uses to send information to the browser is inherently stateless. This means that the server cannot tell whether two requests came from the same person or two different people. It simply processes each request as it occurs, unconcerned with how the information is used by the visitor.

This means that any Web site that wishes to link together functionality across multiple pages requires some type of workaround. Second, server-based processing can only occur after a request has been sent to the server. This means that even the most elaborate server-side scripts can only function in the small interval between the time the user clicks a link or submits a form and the time the dynamic page is returned by the server. Not only does this force server-based processing to be very quick, it eliminates the chance of modifying a page after it has been loaded into the browser. This means that all server-based dynamic Web pages are affected by the bandwidth of the client. The more dynamic a server-based page is the more calls to the server will be needed and the more bandwidth will be required. Visitors with slow connections can become frustrated with the wait for some server-based dynamic Web pages. Browser-Based Dynamic Pages Browser-based dynamic pages use scripts that are included inside HTML pages to give instructions to the browser itself, which generates conditional content. Most browserbased dynamic pages use JavaScript, but other scripting languages, such as JScript or VBScript, can also be used. Chapter 4, “JavaScript and Web Forms,” describes JavaScript and the other browser-based scripting alternatives and how they can be applied to Web forms. All browser-based dynamic Web pages share the same set of basic benefits and difficulties.

The Benefits of Browser-Based Processing Unlike server-based processing, browser-based processing can continue after the page has been loaded into the browser. The content and display of the dynamic elements on the page are not limited to the HTML code that was sent by the Web server. Browserbased scripts can make content appear and disappear, change position, change formatting, and a host of other functions that are not possible using server-side scripts. Additionally, because the processing is handled by the browser and not the server, browser-based dynamic Web pages are not affected by bandwidth. Functionality that might force a server-based page to connect to the server can be handled entirely within the current page by the browser. Other functionality, such as creating pop-up windows or moving the browser window, simply isn’t possible using server-based scripts.

Difficulties Associated with Browser-Based Processing Browser-based processing has its own set of difficulties, some of which are quite significant. First, all browser-based scripts rely on the visitor’s browser to perform the processing. This is significant when you consider that not every browser has the same set of functions and some don’t have any script-processing ability at all. This leaves the developer of browser-based dynamic pages with a choice: limit the functionality of the page to a qualified set of users or spend a significant amount of time creating alternative scripts for many different browsers. Having the browser handle the processing of dynamic content also presents another problem. Most browsers cannot replicate the raw processing speed and flexibility possible using server-based scripts. While browser-based scripts are very good at changing the way data is displayed, they are notoriously difficult when it comes to processing the data itself. Compared to server-based processing, the browser-based alternatives are both clunky and complicated. Also, many visitors could have older or slower machines that handle the browser processing only very slowly and can affect the use of other simultaneous applications. Finally, browser-based processing does not really allow for information to be stored in any permanent way. While small amounts of information can be stored by the browser for a limited time, this information is limited in both size and structure. Only small bits of

text can be stored, and only on some browsers, and only on an individual user basis. Storing more complex information or gathering information from more than a single user is impossible using browser-based scripts alone.

Creating Dynamic Web Forms So, if both server and browser-based dynamic Web pages have advantages and disadvantages, which should you use? And how do these technologies apply to Web forms? The answer to the first question is simple: use both. This way you will gain all the advantages of each and will be able to offset many of the difficulties. The second question is more interesting. The answer is in your hands. The projects in this book will show you how you can apply dynamic Web page technologies to Web forms. These projects focus on three of the basic fundamentals of Web form design: modularity, usability, and functionality. Each has its own benefits and considerations, but before you can learn about dynamic Web forms you should have an idea why you should use dynamic Web forms in the first place. The Benefits of Dynamic Web Forms Dynamic Web forms are the most directly responsive user interface possible on the Web. This might seem like a bold statement, but it holds up to scrutiny. The simple fact is that there is no current alternative that can match the flexibility, power, and low cost of dynamic Web forms. Whether the forms are created using the techniques covered in this book or through some entirely different application, dynamic Web forms go far beyond simple dynamic Web pages. A typical dynamic Web page is only dynamic in one direction—toward the visitor. Using this model, nearly all information passes from the server to the browser, with only simple page requests being sent the opposite way. The addition of Web forms into the equation, however, allows the dataflow to extend in both directions. Dynamic Web forms allow for the processing of information at both the server and the browser. You might compare the difference to the performance of a play. Actors practice and sets are prepared before the performance while audience members buy tickets and take their seats. When the curtain goes up and the play begins the actors can see and hear the reactions of the audience. This allows them to make minor changes—such as adjusting the emphasis of a certain line or tempo of a scene—in how the play is performed. The audience in turn is more likely to react favorably to the play and come away with a better experience. In the alternative scenario, the performance could have been recorded and shown to the audience at a later date. In this case, the actors have no chance to change their performance based on audience reactions and the audience may have a slightly less enjoyable experience. Dynamic Web forms allow you, as the developer, to create a page or a set of pages that can react to the input of the visitors. Beyond simple presentation or content changes, dynamic Web forms give you the ability to change the user’s experience for the better. Alternatives to Dynamic Web Forms Dynamic Web forms are the best way to transfer information between a community of geographically separated users, but it’s not the only way. There are a few alternatives; most are expensive, complicated, or restrictive. For example, recently there has been a movement toward ASPs (Application Service Providers). These companies provide custom applications that allow individuals to transfer information to and from a dataset. The marketing of these companies involves a simple premise: pay us to do all the coding and maintenance so that you can concentrate on the fundamentals of your business. The problem is that for the most part any data information architecture will require a company to pay someone to build and maintain the system. By choosing an ASP to perform this task, you allow this system to be built around proprietary applications or

nonstandardized code. When you need to modify or add to the system you will be forced to deal with the same company at the price they set. In addition, extracting your company from the ASP-designed system can be incredibly difficult. The ASP itself has no motivation for providing a speedy changeover and not even the most benevolent ASP is likely to give you access to the source code for the system. The same problems are evident with using distributed applications to replace dynamic Web forms. Distributed applications are programs that you purchase off the shelf. A good example is Microsoft’s Access, which allows a company to create its own data exchange system. Besides the fact that distributed applications are likely to involve a more highly specialized support staff, they are less likely to be flexible enough to handle all of your business’s needs. You might end up with a dozen small systems each based on a different distributed application rather than a single unified data system. Some companies have recognized this problem and have developed super applications called Enterprise Resource Planning (ERP). An ERP purports to handle all the data processing needs of any company from a single application. How does this work? Simple, just take all of the functionality of two or three dozen distributed applications and cram them together using a proprietary data exchange model. Then charge tens of thousands of dollars for the program and the highly trained specialists required to install it. Finally, provide a few thousand pages of technical documentation and require an upgrade every couple of years. Sounds great for the manufacturers of ERP applications, but is hardly feasible for the vast majority of data systems. Of course, I’m sort of biased when it comes to dynamic Web forms. After all, I did write a book about them—so I’m invested in the technology. But, I think most developers that haven’t developed dynamic Web forms before will be surprised at the power and functionality they provide. I’m sure after you spend a little time researching this technology, you’ll see that there really isn’t any meaningful alternative.

Dynamic Web Form Concepts and Considerations Chapter 2:

Overview It’s really simple to slap some HTML and JavaScript on a Web page and create a dynamic Web form. To create a pleasant user experience, however, you’re going to need to take into account a number of issues. First and foremost: most Web users hate entering information into Web forms. Make that Web form confusing, buggy, or unnecessarily complex and you’ll lose those few visitors who actually do want to fill out the form. Of course, some developers have the advantage of designing for a trapped audience. Intranet developers, for example, can force-feed employees just about anything they please—their end users have no alternative solutions. But even so, happy employees are productive employees, and when they hand out those profit sharing checks you may regret not giving a little more thought to your interface design. A well-designed Web form may not make anyone jump for joy, but a poor design may make the users bang their heads against the keyboard—or worse, take their business elsewhere. A poorly developed Web form is no picnic for the developer, either. User complaints, bug fixes, and workarounds mean more work. Incomprehensible code or a confused development environment can make the hours, dollars, and stress pile up. This chapter covers some of the most important conceptual aspects of Web form design, and a few common practical suggestions to use as you develop your Web form interface. Of course not every project can implement all the suggestions presented here, but it’s still useful for the designer to have a proper grounding in the basics and an understanding of some of the issues involved in creating Web form interfaces. After you’ve completed a few interface design projects on your own, you’ll realize the best gift you can give yourself is to get it right the first time.

Usability If you wanted to put a nail into a piece of wood, what would you use? A rock, a shoe, your own head? It seems simplistic to say that the best tool for hammering is actually a hammer, but this is what usability is all about. Basically, usability breaks down into five simple precepts: 1. Provide the tools. 2. Communicate where the tools are. 3. Communicate how the tools are used. 4. Make the tools work every time for every user. 5. Provide help if the tools don’t work. Seem simple? Well, in the case of computer interface design, developers have been grappling with this process since ENIAC (that is, the Electronic Numerical Integrator and Computer, in case you didn’t know). In Designing Web Usability, Jakob Neilsen—the leading authority on the topic—says, “Bad usability is like having a store that is on the 17th floor of a building (so nobody can find it), is open only Wednesdays between 3 and 4 o’clock (so nobody can get in), and has nothing but grumpy salespeople who won’t talk to the customers (so people don’t buy too much).” Neilsen was talking about the general design of most consumer Web sites and their relation to their users. For Web forms the issue of usability can be simplified even more: bad usability in Web form design is like asking someone to drive a nail with a broken hammer—they may accomplish the task, but they won’t thank you for it. Usability Concepts Don’t expect to become a usability expert overnight. Successful professional interface designers spend many years watching users, studying their behavior, and learning the intricacies of proper user interface design. But though you can’t learn everything, you can learn about usability and how to apply the basic principles to your Web forms.

Interface Any medium whereby two or more sources of information can communicate.

In Chapter 1 I described Web forms as the most directly responsive user interface possible on the Web, but forms are not the only user interface out there. Actually, any Web site is an example of a user interface. Every Web site attempts to supply information to the visitor, and some even gather information using cookies, header information, or server logging. Web forms, however, add another dimension to a Web site. Form users are asked to consciously supply information.

User Interface Any interface where one or more of the primary sources of information is a human.

It is important to understand this difference, as it adds an extra burden to the Web form developer. A Web site whose sole goal is to increase brand awareness can still succeed with a bad design. The site can accomplish the goal, although dubiously, simply by being seen. But even the simplest Web form requires that both the user and the form complete some function. A form that is never filled out is as bad as a form that never works. The first step in designing usable Web forms is research. Perhaps the best place to start is to look for examples of Web forms that don’t work. Undoubtedly you’ve been to a Web site that asked you to fill out dozens of form fields just to add your name to a mailing list. Or a form that claims your e-mail address is invalid, despite the fact you’ve been using it for years. Have you ever tried to back up a page on a multi-page form? Ever fill out a form in order to gain access to a restricted part of a Web site and learned later that you’ve signed up for a newsletter you never wanted? If any of these things bother you, they are sure to bother your users. Looking at other Web forms should only be the first step of your research. It is also very important to study the users. This kind of research is generally termed usability testing. Usability testing is a multimillion-dollar industry that has been used to study everything from how drivers operate their vehicles to how people hold their pens. If your project budget will let you hire a usability-testing firm, by all means do so. But even if you don’t have sufficient funds, take some time to do some user research on your own. The basics of usability testing can be quite simple. Sit down and ask a typical user to perform a series of tasks using the interface. By watching how the user performs each task you can determine problem areas, establish a typical workflow, and generate concepts for improvement. After the tasks are done ask the user questions about the interface: What did you have difficulty with? Was there anything that seemed unintuitive? How could the interface be made better? Some of the most revealing usability testing doesn’t even have to be done on your own interface. If you have a competing product available, usability testing on that can help make yours better. In other cases Web forms are developed to replace older legacy systems. Watch how these old interfaces are used and spend a lot of time talking with the users. After all, these will be the people who’ll come to you if your interface doesn’t do what they need. If you’re really lucky, all that research will give you a priceless gift: an insight into how the user thinks. This leads directly to the second step in usable Web form design: keeping a user-centered mindset. This sounds easy; it’s not. Developers are often tempted to create an interface that is programmatically very simple but ends up being unnecessarily complex for the user. On the other side of the coin, they may feel the need to create a spectacular-looking form that won’t work at all for users of lynx. Of course you can’t always jump through hoops for the users. Sometimes the detriment of having to write 200 extra lines of code outweighs a minor benefit to the user. Creating a form that works on every browser ever made but that puts users to sleep doesn’t help much either. The key isn’t to become a slave to the user, but to keep in mind users’ needs, wants, and expectations. After creating your interface the final step is testing. Skip this step at your peril. There’s far more to testing than simply seeing if your form properly submits the data, although that’s certainly an important part. You must also be sure that the form is actually likely to accomplish the task. Designers and developers, especially the good ones, have a tendency to get drawn into their work. While they are stressing about minutiae they can easily miss glaring problems. Be sure to test both the technology and the user. A round of usability testing should precede any release. Remember: the user is one half of your form interface, and in the final analysis designing and testing for the user will save you more time than it costs. Accessibility It goes without saying that if your users can’t see your form then they can’t use your form. While it is unrealistic to believe that you can design an interface that will work

perfectly for everyone, it is important to try to develop for the largest possible audience. Whenever feasible, offer options for those users with special needs or out-of-date software. Getting users to enter form data is an uphill battle; don’t add to the burden by creating a design that inherently excludes some users. Intranet and extranet developers would be wrong to think that they don’t have to worry about accessibility. Even though you may think you know about all your users, there are always a few unknowns. You may know what brand and version of browser your users have installed, but how long will that last? A browser version change can wreak havoc with client-side scripting and form layout. Are you prepared? What’s the monitor resolution for your users? Is there anyone who is visually impaired? How many of your users have images or cookies turned off? Can your form work for all these people?

Designing for the Visually Impaired I have to wear glasses to drive. A coworker of mine is color-blind. Another requires a special monitor shade to block out low-frequency radiation and glare. Quite a number of people have some kind of peculiarity relating to sight. When designing anything for the Web, especially a form that you want people to use, you need to remember that not everyone has 20/20 vision. Spend a little time surfing the Web and you’ll come to the conclusion that most sites don’t take this into account. Font sizes are often fixed to a small size to increase aesthetics. Graphics are used instead of text because a specific font or effect was desired. Web sites are designed for users of large monitors. Low-contrast or graphical backgrounds are everywhere. These issues are not uncommon, and they can be problems for some users. Most people simply have to make do with what they see on the Web. Recently, however, there has been an increased push toward accessibility on the Web. The U.S. government recently added Section 508 to the Rehabilitation Act. In a nutshell, Section 508 establishes accessibility requirements for any electronic documents or applications developed, maintained, procured, or used by the federal government. In addition, the World Wide Web Consortium (W3C) has begun the Web Accessibility Initiative (WAI), which is designed to promote acceptable Internet functionality for everyone regardless of disability. Find It Online You can find out more about Section 508 and the Rehabilitation Act at the government’s Web site: http://www.section508.gov/. Information about WAI can be found at http://www.w3.org/WAI/. Use the following tips to design for visually impaired audiences: § Never set the font explicitly in pixels or points. Use relative font sizes only. § Avoid using very small fonts. § Use only high-contrast colors for the background and text. Black text on a white background is the best. § Avoid graphical text or buttons whenever possible. If you must use them, be sure to include an “alt” value. § Organize your HTML so that an auditory browser can understand it—auditory browsers read from the top of the HTML down. Tables in particular can produce unintended results. § Consider using CSS aural tags. § Most importantly, talk to visually impaired users and get their input.

Designing for Non-Graphical Users Not everyone can afford to fly on the Concorde, and not everyone has T3 Internet connections. Many users will choose to save bandwidth by setting their browsers to not download images. Others just use a text-only browser such as lynx. In these cases the basic form elements still work, but any graphics will be missing.

Most of us are so used to the graphical nature of the Web that we don’t realize just how integral graphics are as a part of our design. Navigation is often accomplished using image maps. Graphical buttons replace text links. Image roll-overs are commonplace. But what happens to these pretty sites when the graphics go out? Here are a few tips for designing for the non-graphical user: § Don’t use image maps. § Use text links whenever possible. § Include the “alt” value for all images, but don’t rely on it. Many browsers don’t fully display the text, or it may be invisible because of a dark background. § Don’t use images to display information. § Test your interface with the images turned off or on a text-only browser. Find It Online The lynx browser can be found at: http://lynx.isc.org/ or visit http://www.delorie.com/web/lynxview.html for an online lynx emulator.

Designing for Multiple Browsers It’s likely that very few of the users who come to your site will be using lynx. Most will be using some version of Microsoft’s Internet Explorer or Netscape’s Navigator. Anyone who’s developed for the Web has bemoaned the fact that these two companies couldn’t get together on a set of standards for displaying Web pages. But even within a single product there are vast differences. Take, for example, the jump from Netscape 4.7 to Netscape 6. The newest version includes a completely new display and scripting engine. Pages that look one way on version 4.7 look significantly different on version 6. Some users may be using browsers you’ve never heard of. Opera, iCab, Konqueror, Ariadna, HotJava, WebTV, and Amaya are just some of the alternative browsers available. Each one displays HTML and runs JavaScript a little differently. Designing for multiple browsers isn’t as difficult as it seems. Here’s a bit of advice for multi-browser design: § Know your audience. An intranet developer should be able to eliminate all but the most popular browsers from the possibilities. Additionally, Web server logs can tell you a lot about the browsers your visitors are using. § Don’t sweat the small stuff. Don’t spend weeks trying to make the site perfect on one minor browser. It’s likely that any change that will work will adversely affect the site on other browsers. Concentrate on the big browsers. § Test on multiple browsers and platforms. IE 5 looks a lot different on a Macintosh than on a PC. § If possible, provide alternative pages on a per-browser basis. Both server-side and client -side scripts can detect the browser type. If you have the time and resources, use that to your advantage. § Degrade the site gracefully. Provide non-JavaScript alternatives and layouts that don’t require style sheets or tables. Find It Online A treasure trove of old, international, and rare Web browsers is available at http://browsers.evolt.org/. Technical Support Let’s face it: things break. Whether you’re designing cars, buildings, bridges, or programs, eventually even the best-laid plans fall victim to age, inattention, the elements, or simple entropy. Web forms are no different. Databases and servers crash in the middle of the night, new browsers butcher your perfect interface, a key file is accidentally deleted just before the automatic backup, hackers replace your site with a tribute to Bob Barker—these are just a few of the problems you could encounter. While you can’t be ready for every situation, you can keep your user interface responsive and flexible enough to quickly diagnose any problems that occur. All Web forms will break. Accept it. Someone out there will type out their age alphabetically in a field you didn’t think to validate. Another individual will decide to

register his 11-month-old son on your Web site only to receive an e-mail note wishing the infant a happy 101st birthday a month later. An international user will enter a nonGregorian date on an online invoice. Daylight savings time will cause an e-calendar user to miss an important meeting. Of course, just because you know that your Web form will break, that doesn’t mean there’s nothing you can do about it. Your primary defense against problems is data validation. Save yourself a migraine and validate every single field right from the beginning. Validation for Web forms means that the data type and size of a submitted value must fit within the acceptable parameters of the storage medium. In short, if a database field only takes integer values, be sure that the data submitted by the user is an integer. Don’t forget about the size of the data either. Many databases accept no more than 255 characters for varchar fields. Others might have limits on the size of integer values or defined date value limits. Here are a few things to look out for when validating form information. These tips apply to server-side validation. § Never assume the user won’t enter bad data. You’ll discover early on that people are more confusable than you’d think possible. § If feasible, limit the users’ choices using selector elements such as check boxes and radio buttons. § Validate important fields twice: once on the client, once on the server. A little later on I’ll explain the security reasons for this. § Don’t assume that the maxchar attribute or JavaScript functions will limit user input. Some users may be using incompatible browsers and malicious users can easily get around these precautions. The next defense against the inevitable problems is training. Some of the biggest problems for end users are not bugs or errors but simple confusion. If the users don’t know how to properly work the user interface, expect the tech support e-mail messages to pile up. The issues of usability and accessibility discussed earlier can go a long way toward resolving this issue, but even the simplest interface can be trouble for some people. You need to provide a way for your users to learn your interface, find answers to questions, and contact someone who can solve any additional problems. The easiest way to be sure that a user understands how to use an interface is to provide a tutorial. Even intranet or extranet users who have been personally trained by a technician can benefit from an online tutorial. After all, memories are short and not everyone takes great notes. Tutorials can be a simple text-and-image slide show, a dynamic interactive interface, a full-blown multimedia presentation, or anything at all that explains in plain language how to use the Web form application. The best tutorials include a walkthrough of a common scenario using the interface. Professional application developers have long understood the need to provide immediate technical assistance (see Figure 2.1), but sadly this understanding hasn’t transferred well to the Web. For most Web sites and Web forms the only technical assistance is an frequently asked questions (FAQ) page. If done well, an FAQ can be a great resource, but most sites only provide a half-dozen or so questions and answers. Others are crowded with hundreds of questions, leaving the user lost in a sea of unnecessary information. For any truly usable and complex Web form you will need something beyond an FAQ.

Figure 2.1: Windows 2000 and MacOS X Help screens Return again to the concept of a user-centered mentality and think about it from the user’s perspective. A user who encounters a problem at a specific point in a Web form doesn’t want to go to a new page that answers only general questions or is cluttered with answers that don’t apply. Users want help about their specific problem at the specific point in the Web form application. Ideally they shouldn’t have to go to another page or log into a special help site; they want the help in the context of their current situation. Context-sensitive help is not a new idea. Operating systems and applications have used context-sensitive help for years. The concept is to get the information as close to the end user as possible without distracting the user or interrupting the workflow. An obvious (and annoying) attempt at context sensitive help is the Microsoft Office paper clip (see Figure 2.2). “Clippy” provides useful information about the current application, document, or function, and provides links to get more information. It also serves as the entryway for a larger, indexed help system.

Figure 2.2: Everyone’s best friend, Clippy I definitely don’t recommend putting a talking paper clip on your Web form, but I do show a simple context-sensitive example in the third project of this book. Feel free to expand or modify it to meet your needs. Whatever help solution you go with, here are some issues you should consider: § Don’t make the users lose their place by leaving the page to get help. § Provide short bits of information, but give the ability to get more in-depth coverage. § Provide links to FAQ pages, support forums, or contact lists if available. § Be consistent in the way help is accessed, displayed, and used. § Keep the information up-to-date. § Make the system expandable to handle future growth. For an interesting article on one idea of how context-sensitive help applications should look, visit http://www.smountain.com/resource/ContextHelp.pdf. Finally, in case the context-sensitive help, tutorials, and FAQs don’t work, you’ll need to provide a way for users to contact someone to solve their problems or simply hold their hand as they go though a transaction. Hopefully you can provide more than a general customer support e-mail address. If yours is a large project with a big budget you might consider purchasing a toll-free number for 24-hour assistance or developing a real-time, IRC-like communication system for technical support. Even developers of small projects should consider adding a technical support e-mail address to a contact list. Your goal should be to provide the most accurate, timely, and personalized assistance possible.

Security Those who need to spend the most time on security issues are the ones who don’t spend enough time dealing with security. For the Web, security is more than just a strong firewall. It means safeguarding client information, protecting data assets, preventing fraud, and, most of all, creating a trusting relationship between your organization and the users. Perception of Security In terms of the Internet, perception is key. It doesn’t matter if your site is the Web equivalent of Fort Knox, if the users perceive it to be a threat to privacy, pocketbook, or peace of mind they will take their business elsewhere. You must create an environment where the users can feel safe entering credit card numbers or other valuable personal information. The first step in creating a trusting environment is to tell the users how the information is going to be used. Can you think of a reason why some registration forms ask for your Zip

code but not your address? Did you ever wonder why an online bookstore needs your work phone number? Is it really necessary to declare your gender before joining a mailing list? Requests for this kind of information undermine the trust between the users and Web sites. If users don’t know what you’re going to do with a piece of information, their imaginations will create any number of unhappy possibilities. Preventing this can be as simple as providing a separate “how this information is used” page or, even better, text right on the form itself explaining how each field is to be used. You might find that you can easily add this text to an existing context-sensitive help system. Once you start explaining why you need the information, you’ll begin to see the importance of collecting only the information that you absolutely require. Differentiating between optional and required fields is a start, but many users will still make an unconscious connection between this unnecessary information gathering and a threat to privacy. A better option is to completely separate the required and optional portions of any form. For example, to send users an e-newsletter you only need their e-mail addresses. Later on, users could be given the option of personalizing their e-newsletter service by answering a few questions. A similar technique could be used for site registration, forum membership, and online commerce transactions. After you have explained how the information is to be used, you need to reassure the users that unwanted outside forces can’t access the information. You can accomplish this in two steps: provide a functioning privacy policy, and explain the secure server transactions involved.

Explaining Your Privacy Policy Privacy policies are all over the Web. More people are concerned about online privacy than ever before, and the best reassurance a user can have is an effective privacy policy. An effective privacy policy is more than just a page that informs users that their information won’t be sold to a telemarketing firm. A privacy policy should state what information will be shared, how it will be shared, and with whom it will be shared. Give examples of how the information has been shared in the past. Explain the types of privacy restrictions third parties are required to follow. Be sympathetic to the privacy concerns of the user. Write the policy in plain language, not legalese—the personal touch can do wonders. Finally, stick to the policy. Avoid changing your privacy policy unless absolutely required, and never, ever break it. Once trust is lost, it’s ten times harder to get back.

Explaining Server Security The final step in creating a perception of security is to assure users that their information is safe from hackers and other malicious agencies. Internet users are constantly bombarded with news of hackers stealing credit card numbers, personal information, or mailing lists. You need to convince them that this won’t happen to your site. There are hundreds of security options ranging from multimillion-dollar “bank-vault” systems to open source firewalls—and in the end no security system is perfect. From the users’ perspective, however, it doesn’t really matter what the security measures are, just that you have taken the time to consider the issue and are prepared for any attacks. This doesn’t spare you from creating the most secure transaction system feasible for your project, but it does mean that you need to consider how to communicate your security to the user. Giving precise product and version numbers of your security products is an invitation to hackers, but you can explain the types of products and technologies you use to protect sensitive data. Stress your dedication to security and your sympathy with users’ concerns. Give an account of your site’s security history. Has the site ever been hacked? What information was compromised? What steps have been taken to ensure it won’t happen again? Express your confidence in your security, but don’t be boastful.

Secure Sockets Layer (SSL) Some users never feel safe transmitting personal information across the Internet. Savvy users know that third parties can intercept unsecured transactions, but secured transactions can be reasonably safe. The basic rule of thumb is that any transaction involving money (including e-commerce), sensitive personal information (contact information, medical history, employment history, and the like), or confidential business information should be handled using a secure transaction system. Secure Sockets Layer (SSL) is the most common way of securing an Internet transaction. Developed in 1994 by Netscape, SSL is an open standard that uses a system of public and private keys transmitted between the client and server. SSL uses a certificate system to allow the client to verify the identity of a server. Only a designated Certificate Authority (CA) can issue SSL certificates. The client is alerted to any outdated or invalid certificates. The latest version of SSL uses the same system for servers to validate the identity of a client. Finally, SSL mandates that all information that is transferred between client and server be encrypted before transmission. SSL has a number of functions to determine whether a transmission has been tampered with. The first step in setting up an SSL connection is to provide a Certificate Signing Request (CSR) to a CA. The price of SSL certificates varies from authority to authority, but expect to pay between $100 and $200 per year. The CA will provide you with an SSL key certificate. This key is the file that allows your server to decrypt data transferred from the client and allows clients to validate the server identity. Using certificates to validate client identity is optional and can be a bit more complicated. To create an SSL client certificate, each user must submit a request CSR to the CA. These certificates are stored within the browser and are not transferable. Most transactions do not involve client validation, but business-to-business interfaces and some intranet solutions should consider using that approach. Tip A number of applications allow a server to be its own CA. While this isn’t recommended for public sites, interfaces that require client validation can save a lot of money by issuing their own SSL certificates. After the certificates have been established, the Web server needs to be configured to use SSL. See your server documentation for instructions on accomplishing this. Typically specific directories or pages will be marked as secure and will activate an SSL transaction, while the majority of the site is unsecured. SSL data is transferred using HTTPS. HTTPS is the set of transfer protocols that determines encryption and transmission of data through SSL from client to server. All of the latest browsers and servers support SSL. Data Validation Beyond data encryption and certificate authentication, developers of Web forms have to take into account straight data validation. An SSL certificate can’t prevent a user from entering data that will, intentionally or otherwise, bring your interface to its knees. The only protection against dangerous data is validation.

When to Validate This book is designed to allow a developer to take advantage of the full power of Web forms by using a combination of client - and server-side scripting. Throughout, the emphasis is on combining the needs and wants of the user with the functionality the developer desires. This concept should apply to data validation as well. First, validate the basic form contents on the client using JavaScript. The client should not have to wait for a call to the server to find out that the password field requires more than two digits. Client-side validation assists the user, who benefits from the faster, more context-sensitive responses. Client -side validation does not need to be as strenuous as

the server-side validation covered earlier, but it should be used for the more common mistakes. Dates should be checked for proper formatting, submitted text should be checked for proper size, integer values should be reviewed against possible values. Next, validate on the server. Earlier I covered the basic concepts of server-side validation, but from a security standpoint server-side validation takes on a new urgency. Web form interfaces that do not use SSL are particularly vulnerable to security breakdowns relating to a lack of proper server-side validation. All the client-side scripting in the world won’t prevent a hacker from copying the source code and modifying the JavaScript. Revalidating the data after submission is the way to prevent an attack like this from being successful.

How to Validate The validation process includes three steps: 1. Validate that all required fields have been submitted. 2. Confirm that each field contains the correct type and format of data. 3. Determine that the data itself is correct. The type of scripting language you use for validation isn’t important as long as you include all of these steps. Here are a few security considerations to keep in mind when validating Web forms: § Don’t trust data in hidden fields. Never use a hidden field for product prices, SQL commands, or tamper-sensitive information. Hidden field values are very easy for a hacker to manipulate. § Don’t rely on form values for more than the basic information. For example, an e-commerce site that uses a form to submit a sale should submit only the product name or ID and the quantity. Price, tax, and product information should not be submitted in a form. Otherwise a malicious user could change data that should remain static. § Always hash data before submitting to a database. Hashing data means escaping out special characters such as double quotes and brackets. Hackers can always try to enter unwanted JavaScript or SQL commands into text fields, and hashing prevents these commands from being executed.

Best Coding Practices If you were to take a look at my office you’d see open books scattered about the room, along with index cards, sticky notes, papers, writing implements, office supplies in various states of repair, and computer equipment (working and otherwise). The system works for me because I use my office on a daily basis and I’m the only one who ever goes in there. If you’ve got a great memory and are the only developer on a project you might be able to get away with that kind of clutter in your code. The rest of us need to organize, standardize, and label. Each development team or individual should define—before the project begins—a set of best coding practices. This document defines the steps in the development process and explains the required procedures. The advantages of a defined process are obvious. Developers can easily fix, update, and use each other’s code; the workflow isn’t hampered by duplicated work or split resources; and locating and fixing code-based problems is streamlined.

Code Commenting and Formatting Imagine an interstate highway system without any road signs—that’s what working with uncommented, sloppy code is like. It becomes easy to get lost and valuable time is spent simply figuring out what is going on.

Commenting Code commenting is a lost art among Web developers. Most scripts have little more commenting than a copyright notice at the top. You can take this one of two ways: Web developers are overworked and underpaid and simply don’t have the time or resources to spend commenting code—or Web developers are shortsighted and lazy. I think it’s a combination of both. No one likes to spend valuable coding time documenting how each and every function or subroutine works, but commenting can be invaluable. First, commenting makes the original developers think about their code in terms of how others will view and use it. This alone is a reason for enforcing a commenting policy. Many developers will produce cleaner, less buggy, and more sophisticated code when they take the time to comment each code step. Second, commenting makes it easier to remember what code does. Many times I’ve come back to a tricky code block after a long weekend only to discover that I don’t remember where I was in the script. It’s more than just remembering the exact bookmark; I’ve forgotten the thought process that I was exploring and the options that I’ve already tried. Commenting allows developers to easily pick up where they left off. Finally, and most obviously, commenting makes code easier to understand. Take the following block of JavaScript: function move(f,truefalse,sName) { var el = f.elements[sName]; var selectedItem = el.selectedIndex; if (selectedItem==-1){ alert("You must first select the item to reorder.");} else { var nextSelectedItem = selectedItem+( truefalse? -1 : 1); if (nextSelectedItem=el.length) { nextSelectedItem=0;} var oldVal = el[selectedItem].value; var oldText = el[selectedItem].text; el[selectedItem].value = el[nextSelectedItem].value; el[selectedItem].text = el[nextSelectedItem].text; el[nextSelectedItem].value = oldVal; el[nextSelectedItem].text = oldText; el.selectedIndex = nextSelectedItem;}} Anyone trying to modify this function would have to work through it step by step. Each parameter would have to be traced through the function. Control structures would have to be evaluated. In short, unfamiliar developers would have to recreate the entire functionality inside their heads. This adds time and frustration to any project.

Here are some recommendations to use when developing a commenting policy: § Standardize your comments. Put them in the same place every time. Make them easy to find. § Describe the purpose of each page, function, subroutine, class, or code block. § Label variables the first time they occur in the document and the first time they occur in each function. § Explain control structures such as loops and conditionals. § Describe the destination and content of any output. § Explain the source and content of any input. § Include a large comment block for any major overhauls or changes. § Sign and date all code.

Formatting Don’t underestimate the ability of sloppy code to waste your time. Any minuscule amount of time that a developer might save by not putting in a few regular blocks of spaces is eclipsed by the hours another might waste trying to figure out a series of nested if statements. Formatting is all about readability. As an example, look at the JavaScript from earlier, now that it’s been formatted and commented: /* This function runs the up and down buttons that reorder a select box. Passes through the name of the form (objForm), whether to move up (boolUp) and the name of the select box (strElementName). */ function move(objForm, boolUp, strElementName) {

var objSelectBox = objForm.elements[strElementName]; // objSelectBox = the select box var objSelectedItem = objSelectBox.selectedIndex; // objSelectedItem = the selected option in the box if (objSelectedItem == -1) // ensures that an option has been selected. { alert("You must first select the item to reorder.") // this error message appears if no option has been selected to move } else { if (boolUp) // determines whether to move Up (backward) or Down (forward) in the element

array { var objNextSelectedItem = objSelectedItem - 1; // objNextSelectedItem = the previous option } else { var objNextSelectedItem = objSelectedItem + 1; // objNextSelectedItem = the next option } if (objNextSelectedItem < 0) // determines if option to move is at top (beginning) of the select box

{ objNextSelectedItem = objSelectBox.length - 1; // change objNextSelectedItem to the last option } if (objNextSelectedItem >= objSelectBox.length) // determines if the option to move is at the bottom (end) of the select box {

objNextSelectedItem = 0; // change objNextSelectedItem to the first option

} var strOldVal = objSelectBox[selectedItem].value; // strOldVal = the value of the originally selected option var strOldText = objSelectBox[selectedItem].text; // strOldText = the text of the originally selected option objSelectBox[objSelectedItem].value = objSelectBox[objNextSelectedItem].value; // replace the value of selected option with value of a neighbor option objSelectBox[objSelectedItem].text = objSelectBox[objNextSelectedItem].text; // replace text of the selected option with value of a neighbor option objSelectBox[objNextSelectedItem].value = strOldVal; // replace value of a neighbor option with value of the selected option objSelectBox[objNextSelectedItem].text = strOldText; // replace text of a neighbor option with text of the selected option objSelectBox.selectedIndex = objNextSelectedItem; // select neighbor option, which now has value and text of original option } } Yes, it takes up a lot of room and the comments are a little verbose, but now even someone who has no experience with JavaScript can follow the code. Actual developers should be able to jump in and begin making changes in mere seconds. The formatting conventions you use should be tailored to needs of the development team, but here are a few suggestions: § Add extra empty lines around functions, subroutines, classes, and code blocks. § Section control structure using tabs or multiple spaces. § Avoid programmatic shortcuts if possible. § Avoid splitting up a process unnecessarily. For example, when you declare long strings, don’t use multiple declarations and concatenation operators when a single declaration will do. § Put comments on their own line. § Put spaces around operators. § If quotation marks, semicolons, or other code elements are optional, either always use them or always leave them out. Naming Conventions Call me Dan, or Daniel, or Danny, or son, or buddy, or dude (just don’t call me Ishmael). When it comes to people we can pretty much call them anything we can get away with, but as you’ve learned, proper coding is all about standardization. Before two developers can work together on a project they have to agree on what the project entails—they have to define it.

Naming conventions give you a way to define the common elements of a scripting environment so that developers can communicate using the same basic parameters. In a way it’s like defining the grammar that developers should use. Hopefully, they already have the vocabulary; that may be enough to get basic ideas across, but only an organized and defined grammar system can facilitate complex communication.

File System Naming Conventions Naming conventions must start at the file level. More than once, on projects with disorganized file systems, I’ve spent more time tracking down where the problem code is than actually changing it. A properly organized file system and naming convention can give a developer a head start on tracking down problems. Additionally, file systems are among the more difficult parts of a Web site to change after it has been established, so getting the structure correct from the beginning is critical. Each file system convention should be tailored to the specific project, but here are a few recommendations: § Divide the pages of code along the same lines as the Web site. A folder should exist for each of the major areas of the site. Global code should have its own folder. § Consider separating the following types of pages into different folders when possible: server-side scripts, client-side scripts, HTML, CSS or other style elements, and Flash or Shockwave files. § Images should always have their own folder at the root level. Divide images up based on type rather than page (headers, form elements, navigation, and so on). § PDFs, movies, audio files, executables, and other media files should all have their own folders. Once you have a file system ready, you can put your files into it. Now, however, you need to consider what to name those files. It would be nice to name files in great detail— say, This_Code_Works_The_Search_Function.php—but most developers are a little more pragmatic than that. Considering that many developers work from the command line, where they have to type in file names by hand, it is not surprising that file names are often truncated. You have two choices when it comes to naming files: let all the developers name the files as they create them and hope that the chosen names have some kind of vague relation to the actual function of the page, or create and enforce a file naming convention. I’ve seen what happens when developers are given a free hand. On a recent project two different displays of an “Ask the Experts” section were called for: a normal display and a smaller teaser. The developer decided to name the files bigask.php and smallask.php. So naturally whenever anyone had to make a change to the page the developer would be told to modify “that bigask file.” Good for a laugh, but not very informative. Here are a few things to consider when developing a file naming convention: § If some of your users have older browsers, then images should be named with the eight -dot -three format. Some of the older browsers versions won’t accept longer names. § Name display and formatting pages as close to the actual URL as possible. For example, if a page is located at www.mydomain.com/catalog/books/, name the display file books.html and the formatting page books.php. § Mark files that are included with an initial “i”, as in i_global.php, i_ formFunctions.js, i_style.css. § Use a defined set of extensions: JavaScript (.jss or .js), CSS (.css or .cs), HTML (.html or .htm), PHP (.php), ASP (.asp), ColdFusion (.cfm). § Capitalize every word after the first. For example: catalogByDate.php, confirmTransaction.html, i_validateUser.js.

Caution

Remember to use the correct file capitalization inside your code as well. Even if you’re not using Unix, your users might be.

Function and Object Naming Conventions The next step in the naming convention process is to standardize the names of functions and other programming objects. Scripting languages tend to have many built-in functions and objects. Sometimes it can be difficult for a developer to tell if a specific function call is referencing a built-in or custom-defined function. A function naming convention can solve this problem. Additionally, a function naming convention can make it easier for a developer to determine the general purpose of a function. Note The class-based system of JSP makes it possible to overwrite built-in classes—and often requires that built-in classes be overwritten. Also, multiple classes can have the same name. This makes sticking to a JSP class naming system extremely difficult. Likewise, ColdFusion doesn’t allow for user-defined functions. Developers who are dedicated to these scripting languages should skip ahead to the next section on variable naming. Below are a few function and object naming basics that I use to keep my code organized. Of course, these are just suggestions. § Capitalize every word after the first. § Mark user-defined functions with a preceding “f”, as in f_getData(). § Mark user-defined objects and classes with a preceding “o”, as in o_catalogItem. § Designate functions that modify the external environment with a trailing “x”, as in f_swapImage_x(). § Designate object and class methods with a preceding “m” and use “p” for object properties. Chapter 3 includes some suggested rules for naming form elements and other HTML objects.

Variable Naming Conventions The final stage in developing a naming convention is to define to proper syntax for variables. Variable naming is an extremely common part of any coding process, so developing proper procedures can make a big difference in the readability of code. Beyond making code dramatically easier to understand, variable naming conventions often prevent bugs such as improper variable capitalization, misplaced variable scope, and accidental reuse of a variable name. I recommend giving variables a prefix based on the (most likely) data type. Table 2.1 provides a breakdown of some sample prefixes—but note that not all scripting languages use all data types. Table 2.1: Variable Prefixes Data Type

Prefix

Example

byte

byte

byteTool

short

shrt

shrtField

integer

int

intLocation

long

long

longMole

float

flt

floatPi

double

dbl

dblMolePi

character

char

charFirstLetter

Table 2.1: Variable Prefixes Data Type

Prefix

Example

Boolean

bool

boolTrue

date

date

dateYesterday

point

pnt

pntLocation

time

time

timeNoon

void or null

void

voidNull

string

str

strName

hexadecimal

hex

hexRedColor

octal decimal

oct

octIPAddress

array

arr

arrFormElements

object

obj

objTextBox

variant or unknown

var

varUserInput

Additionally, here are a few suggestions to consider when creating a variable naming convention: § Capitalize each word. § Name constants in all caps with underscores between words. For example: SERVER_NAME, BACKGROUND_COLOR, PAGE_NUMBER. § Avoid numbering variables. § Loop counters can be single characters. For example: for (k = 0; k < 9; k++), where k is the variable. § Popular global variables should be noted: intGlobalBrowserVersion. § Variables limited in scope to a single function or class should be indicated: intSwapOldSRC, intSwapNewSRC. § Make the names accurate and meaningful. Version Control Now that you’ve assured yourself that every developer on your project speaks the same language, you need to make sure that they’re not all talking at once. Version control is a way for a project team to coordinate the modification of source files. A good version control system has two functions: it ensures that multiple users do not attempt to modify the same file at the same time, and it provides a way to track changes to source code.

Concurrent Version Control Have you ever seen two ball-players crash into each other at high speed while trying to catch the same pop-fly? Ever imagined how that must feel? Well, the same type of sensation occurs (without the bruises, of course) when two developers try to modify the same source file at the same time. Changes are made by one programmer, then undone by another, then remade by the first only to erase the changes of the second. Inevitably, this leads to increased project times and hotter tempers. Concurrent versioning can prevent one developer from stepping on the toes of another. Concurrent versioning is a process that lets developers share control of different versions of files in a common repository of files. A developer will typically download or “check out” the latest version of the source code. After changes are made the source code is checked against the latest version of the file in the repository. If another developer has made a change to the same file a warning is given. Concurrent version

software typically marks the specific sections of code that are in conflict. These conflicts can then be investigated and merged or discarded if necessary.

Revision Control Who modified that file? When was that change made? Is the unmodified code still available? These are the types of questions that a revision control system can provide. Revision control involves marking source code files with the name of the developer and the date each time the file is modified. Each change is documented allowing a developer to restore code that has since been modified. Revision control systems work much like concurrent version systems in that typically a developer checks out a file or a set of files, makes changes, and then submits the files back to the repository. The revision control application notes what section of the code has been modified and marks each file with the developer’s name, the date, and any notes that the developer may choose to leave regarding the changes. These notations are made available through the revision control system to any user who requests them.

HTML Forms

Chapter 3: Any Web-based form begins with HTML. As a Web developer you no doubt already have a good grasp of how HTML works. This chapter will simply review the HTML tags associated with Web forms and give a few introductory examples of how these form elements can be used. Many of these examples use JavaScript, but don’t worry if you aren’t very skilled in using client-side JavaScript; these are just quick samples of what is possible. Chapter 4 will explore JavaScript and its use in Web forms in more detail. Experienced HTML coders can skip this chapter, but you might want to take a look at the example files, as some of the techniques may be new to you.

Form Elements Before you learn about the individual form tags and elements it is important to understand how HTML forms work. Web forms pass information to the server in namevalue pairs. This means that the name of each part of the form is linked to the corresponding value. Values can be user-entered text, a selected option, hidden variables, a file location, or similar information. The processing page or application can then reference the submitted value through the assigned name from the form. Namevalue pairs are submitted to the server either in the requesting URL or in the page header, depending on the method attribute assigned to the FORM tag. Each part of the form is called an element. Elements come in four types: control elements, text input elements, selectors, and special elements. Each element has a number of properties that can be assigned. These properties are called attributes. In this chapter attributes in bold are mandatory, and text in italics represents an example of a possible attribute value. For example, in this code text:

Type=hidden and name are mandatory while formHidden and Hidden Value are sample values. The Form Tag Every HTML form begins and ends with the FORM tag. The FORM tag names the form and defines the server-based page or program that will process the form information. The basic structure of this tag is as follows:





Following are brief descriptions of the most common attributes for the FORM tag: § action. This attribute holds the URL of the processing Web page or application. The URL can be relative (../cgi-bin/form-processor.cgi) or absolute (http://www.premierpressbooks.com/search.php). action is the only required attribute of the FORM tag. The action attribute can also be set to a mailto value. A form with a mailto action will use the visitor’s own e-mail software to submit the form via e-mail. Most of the time this results in a security warning like the one shown in Figure 3.1. Most form designers get around this by submitting the data to a processing page that can create e-mail using a server-based e-mail client.

Figure 3.1: A mailto form security warning § name. Use this attribute to give the form a unique identifier. Client- or server-side scripts can then use this identifier to distinguish form elements and values specific to each form. The use of this attribute has mostly been deprecated in favor of the id attribute, but some older browsers and server-side scripts don’t recognize id. To prevent potential errors, it’s a good practice to always include identical name and id attributes for the FORM tag. § id. This is an attribute for establishing a unique identifier for the FORM tag. This attribute can be used by CSS and JavaScript to reference a specific form. § target. This attribute determines the frame or window in which the form-processing page will appear. For example, a Web page that has a search form in a navigation frame can make the search results appear in the main body frame. Possible values of the target attribute are: "_self" (the same window/frame), "_top" (breaks out of a frameset and places the resulting page in the current window), "_blank" (opens a new window for the results), "_parent" (opens the results in the parent frameset of the current window), windowName (opens the results in the named window), frameName (opens the results in the named frame). The default value is "_self". § title. Use this attribute to assign text to the FORM tag. This text can be used for context-sensitive help, tool tips, or as accessibility instructions for auditory browsers. § enctype. enctype sets the MIME type used to post the form data on the server. For most forms this value is application/x-www-formurlencoded. Generally there is no reason to assign this value, as it is the default used for Web forms. Other possible values include multipart/form-data (used for forms that include files), and text/plain (used for mailto forms). § method. The method determines how the data is submitted to the server. The default value, get, appends the name-value pairs to the URL. The processing page can then retrieve the form information through the environmental variable (QUERY_STRING) or by parsing the URL string. As the length of any URL is limited the get method should only be used for short forms with limited user input. The most common usage of the get method is in search forms. With a get form the resulting pages can be bookmarked or shared without requiring the form to be reentered. The post method sends the form data to the server in the HTTP Header. The submitted form information is hidden from the

user and the processing page cannot be bookmarked or shared with the form information intact. The post method should be used on any form that uses the fileupload, textarea, password, or hidden form elements. § accept-charset. Use this attribute to specify the character set that the processing page or program should accept. Multiple character sets are comma delimited. The default value is ISO-8859-1. You should use this attribute if you expect your users to use multiple or unusual character sets, such as Japanese or Korean. The FORM tag can accept style attributes such as class and style and the standard event attributes such as onClick, onMouseOver, and onMouseOut. Additionally, two FORM specific event attributes are available: onSubmit and onReset. OnSubmit is fired when the form is submitted. The most common use of this attribute is to validate form input through JavaScript on the client. By combining the onSubmit attribute with JavaScript and the return false command you can prevent the form data from being submitted unless specific conditions have been met. Note The file name and contents are reprinted here for your convenience. Throughout this book you will find similar references to files located on the Web page for this book, at http://www.premierpressbooks.com. confirm-form.html

Confirming the Form Submission







The onReset attribute works in the same way, except that it is fired when the form is reset, either from a reset button or a script command. This attribute can be used to confirm the deletion of entered data or to reset JavaScript variables to the initial values. Control Elements Form control elements include the following input types: submit, reset, button, and image. Unlike the other form elements, these do not collect user information. Rather, they allow the viewer to control the actions of the form itself. These elements can be used to submit the form, clear the form contents, or fire JavaScript functions.

The Submit Button The submit button is the most common of the control elements. It represents the easiest way—and for non-JavaScript browsers the only way—to submit a form and send the data to the processing page or program specified in the action attribute of the FORM tag. Clicking the submit button also fires the onSubmit event for the form. The basic structure of this tag is

Here’s a breakdown of the attributes available for the submit button: § name. Use this attribute to give the submit button a unique identifier. Control elements are the only form elements that do not require the name attribute. § id. This attribute can be used by CSS to reference this element. § title. Use this attribute to assign text to the submit button. This text can be used for context-sensitive help, tool tips, or as accessibility instructions for auditory browsers. § value. The value of a submit button serves two purposes. First, value represents the text that appears on the button. This text should be instructional and unique. Second, the value of this attribute is posted to the server with the rest of the form data. This allows forms to have multiple submit buttons. The server-side processing scripts or programs can use the value attribute to determine which submit button has been pressed. Here’s an example of a form with two submit buttons:

submit-form.html

Double Submit Buttons





Additionally, IE offers a number of browser-specific attributes designed to improve usability, such as notab, tabindex, and accesskey. These attributes and the crossbrowser JavaScript alternatives are discussed in Project 1. A submit button can also accept style attributes, such as class and style, and the standard event attributes such as onClick, onMouseOver, and onMouseOut. Caution Do not confuse the onClick event of the submit button with the onSubmit event of the FORM tag. With some browsers, clicking a submit button with an onClick event will post the form regardless of the results of the activated JavaScript function. For this reason you should always use the onSubmit attribute to validate form data on the client.

The Reset Button The reset button is another common control element. As the name implies, the reset button is the easiest way to reset (clear) a form. Clicking the reset button also fires the onReset event for the form. The onReset event removes all data entered by the user and returns the form to the default state. The basic structure of this tag is

The reset button uses the same attribute set as the submit button.

Other Buttons Not all buttons need to submit or reset a form. As discussed in Chapter 1, using clientside scripting also allows you to perform a large number of actions within the browser. While you can apply JavaScript functions to all form elements, buttons are the most intuitive for the end user. The general button tag can be written like this:

The button element uses the same attribute set as do the submit and reset buttons. However, the button element is nonfunctional without an onClick or other event attribute. The most common use of a form button is to activate JavaScript functions. Here’s an example of a possible use of a button element:

date-form.html

Date (General) Button

Date:



Form Images The standard types of buttons don’t give much flexibility in appearance. CSS and JavaScript can change the color, size, and position of form buttons, but that’s all. Sometimes—for aesthetic appeal or usability—a graphic button is preferable. This is where the input type image can be used to replace the submit button. As with the submit button, clicking on a form image will send the data to the processing page or program specified in the action attribute of the FORM tag. Unlike the submit button, the form image will also send x and y coordinates of the mouse position. The form image tag can be written like this:

The form image tag uses all the attributes of the submit and reset buttons, and has a few additional ones: § src. This attribute specifies the location of the image file. The URL can be relative (../search.gif) or absolute (http://www.premierpressbooks.com/ tech/images/go.gif). § alt. This attribute works just like the alt attribute for the IMG tag. Those users unable or unwilling to view images in their browser can still read the alt tag value. § align. Identical to the align attribute of the IMG tag, this attribute specifies the alignment of the form image. § width. Sets the width of the form image. § height. Sets the height of the form image. § hspace. Sets the horizontal spacing, in pixels, of the form image. § vspace. Sets the vertical spacing, in pixels, of the form image. § border. Sets the border width, in pixels, of the form image. § usemap. This attribute specifies the URL and name of a client side image map to use with the form image. By reading the x and y coordinates submitted with the image element, you are able to determine what part of the form image the user clicked on. Here’s an example of this process in action:

image-form.html

Choose a Square Image Button



Choose a square:



While this page uses client-side JavaScript, the same principle can be used with serverside scripts to generate CGI-free server-side image maps. Text Input The most basic function of online forms, or any form for that matter, is to gather user input. Text is the most versatile of all user input types. Text input elements can accept large amounts of information. This information can be put to any number of uses, including search terms, user names, addresses, passwords, e-mail text, and more.

Single-Line Text Fields By far, the most used text input element is the simple text field. This text field produces a single-line input box. Because it doesn’t have scroll bars or accept carriage returns, the single-line text field should be used only if you anticipate user input of 100 characters or fewer. This is just a general guideline, of course; you can have any character limit (or none at all) if you wish. The text field tag can be written like this:

Here’s a breakdown of the attributes available for text fields: § name. Use this attribute to give the text field a unique identifier. This is the first part of the name-value pair that is posted to the server when the form is submitted. § id. This attribute can be used by CSS to reference this element. § title. This text can be used for context-sensitive help, tool tips, or as accessibility instructions for auditory browsers. § size. This attribute determines the width, in text characters, of the text field. Because the width (like the height) is affected by font size and type, different browsers and users may see different-shaped text fields even when the size is expressly set. § value. This attribute represents the text inside the text field. This information is attached to the name attribute and sent to the server when the form is posted. § maxlength. This number is the maximum length in characters that the text field will allow. § disabled. Adding this attribute to the INPUT tag prevents the user from changing or submitting the text (value) of the text field. This attribute only functions in IE 4+ and Netscape 6. Additionally, IE offers a number of browser-specific attributes designed to improve usability, such as notab and tabindex. These attributes and the cross-browser JavaScript alternatives are discussed in Project 1. A text field can also accept style attributes such as class and style, and the standard event attributes such as onClick, onMouseOver, and onMouseOut. Additionally, three other event attributes are available: onFocus, onBlur, and onChange. onFocus is fired when the insertion point is moved inside the text element. onBlur is fired when the insertion point is moved out of the text element. onChange fires when the user changes the text (value) of the text field. One possible use of these attributes is to simulate the effect of the disabled attribute.

text-form.html

Disabled Text Form







Note

While the script in text-form.html can prevent users from changing the value of the text field, its effect is different from that of the

disabled attribute; with the script, the value of the text field is still posted to the server when the form is submitted.

Password Fields Sometimes security or privacy concerns require that text entered into a form not be displayed on the screen. This is where the password field can be most useful. The password field works exactly like the text field except that the text (value) entered into the field is not displayed on the page. Instead, asterisks or bullets appear in the field. A password field can be written like this:

It is important to understand that this information is not encrypted or otherwise secured in any way. Any data entered into a password field is submitted with the rest of the form as standard text and is therefore vulnerable to security and privacy concerns. To prevent this, be sure to place any form that includes elements that should be secured on a Secure Sockets Layer (SSL) Web page, as described in Chapter 2.

SSL Secure Sockets Layer (SSL) is an Internet protocol developed for the exchange of secure information over the Web. SSL works through a combination of private and public keys that encrypt and decrypt data. For more information, visit http://home. netscape.com/security/techbriefs/ssl.html.

Multi-Line Text Areas One line of text isn’t always enough. When your form requires multiple lines of user input, the TEXTAREA tag is the way to go. This element has many of the same features as the text field, yet has a number of distressing limitations. For instance, the TEXTAREA tag has nothing like a maxlength attribute, so there’s no built-in way to limit user input the way you can with a text field. The TEXTAREA tag can be written like this: Initial Value The name, id, disabled, and title attributes are the same as with the text and password elements. In addition, the TEXTAREA tag has a few unique attributes: § cols. Specifies the width of the text area. Netscape browsers specify this in characters. IE uses its own algorithm roughly equivalent to 10pixel units. Because the width is rendered differently, users may see different -sized text areas depending on their browser and platform. § rows. Specifies the height of the text area. All browsers specify this in characters, but Netscape browsers can add extra space. Netscape browsers are also affected by the current font size and face, while IE requires style tags to change the font inside the text box. Because the height is rendered differently, users may see different-sized text areas depending on their browser and platform. § wrap. This attribute determines how the text inside the text area behaves. "Soft", the default value for IE, wraps the text when it reaches the edge of the text box. "Off", the default value for Netscape,

places carriage returns only when the user enters them into the text box. The multi-line text area can be frustrating to fit in a complex site design. A number of factors can make the area too big in some browsers and too small in others. The best way around this is to use the cols and rows attributes to assign the best height and width for Netscape browsers, and then use style tags to assign dimensions for IE. You’ll never be able to make the text area look exactly the same in all browsers, but you can get close. Following is an example of a page that uses this technique (check it out in a number of different browsers, as in Figure 3.2):

textarea-form.html

Text Area Form


This is a text box




Figure 3.2: Textarea-form.html on different browsers Selectors Selector form elements allow the form designer to limit the user to a specific number of preset responses. Common uses include forms elements that ask for information on gender, state or province, age, and income level. The three types of selector elements available for HTML forms are radio buttons, check boxes, and select boxes.

Radio Buttons Radio buttons allow the user of an online form to select one and only one option from a list of possibilities. Because a long list of options creates a lot of radio buttons, they are best used when the number of options is low (say, two to six). A radio button can be written like this:

Radio buttons have the following attributes: § name. Use this attribute to give a group of radio buttons an identifier. Each radio button in the group should have the same name. When the user selects one button the others are deselected. This is the first part of the name-value pair that is posted to the server when the form is submitted. § id. This attribute can be used by CSS to reference each individual radio button. § title. This text can be used for context-sensitive help, tool tips, or as accessibility instructions for auditory browsers. § value. This information is attached to the name attribute and sent to the server when the form is posted. Unlike other form elements, selectors do not make the value attribute visible to the form user. § checked. The checked attribute designates the pre-selected element. Additionally, IE offers a number of browser-specific attributes designed to improve usability, such as notab, tabindex, and accesskey. These attributes and the crossbrowser JavaScript alternatives are discussed in Project 1. A radio button can also accept style attributes such as class and style and the standard event attributes such as onClick, onMouseOver, and onMouseOut. Additionally, three additional event attributes are available: onFocus, onBlur, and onChange.

onFocus is fired when the user selects any element in the element. onBlur is fired when the insertion point is moved out of the element. onChange fires when a new element is selected. Radio buttons interact strangely with some browsers on pages with background colors. In older Netscape browsers a white box appears around the radio button. To get around this, assign a matching background color using the style tag.

button-form.html

Radio Button Form















Check Boxes Check boxes allow the user to give a true or false response to any query. Unlike radio buttons, check boxes can be deselected, allowing the user to enter a new preference. Also, by adding multiple check boxes, the form designer allows the user to select multiple options. Check boxes are most commonly used on Web forms to opt in for newsletters, select optional extras for products, or modify display preferences. Check boxes are written like this:

The id, value, title, checked, style, and event attributes work exactly the same with check boxes and they do with radio buttons. The only difference is with the name attribute: § name. Use this attribute to give the element a unique identifier. This is the first part of the name-value pair that is posted to the server when the form is submitted. By combining the onClick event with some JavaScript you can simulate the effect of the onChange event.

checkbox-form.html

Radio Button Form

What is your annual salary?

under $20,000
$20,000 - $50,000
$50,000 - $100,000
Other



Select Boxes Select boxes are the most versatile of the form selector elements. With select boxes the user can select a single item or multiple items. Select boxes can save space on the page by holding the entire list of options inside a drop-down list, and they can give a clearer picture of the selections available by displaying multiple options at once. Select boxes are often used for site navigation, to set search options, or to designate a product option. A select box can be written like this:

This is an option

The id, name, value, title, style, and event attributes work exactly the same with select boxes as they do with check boxes. The select box, however, has a number of additional attributes: § size. This attribute specifies the number of options that are visible at one time. If no size is given or if the size is set to 1, all the options will be hidden in a drop-down list. The size should always be more than 1 if multiple selections are allowed. § multiple. By designating a selected box with the multiple attribute you allow the user to select more than one option by holding down the Ctrl (Command on the Mac) key while clicking on additional selections. Holding down the Shift key allows the user to select multiple consecutive options. § selected. This attribute is assigned to the option that should be selected by default when the page loads. IE 4+ allows you to specify the width and line height of the select box using the style tag. Netscape browsers, however, set the width and line height from the appropriate font tag and the size of the largest option. To work around this, you can create an unselectable option at the end of the select box that is the width you desire. This can be accomplished using the onChange attribute of the SELECT tag and a little JavaScript.

select-form.html

Select Box Form



This is an option This is another option Yet another option

The final option ———————————————



Special Form Elements There are two additional types of form elements that do not fit in any of the other categories: hidden and fileupload. The hidden element holds information that the end user should not see or does not need. The information stored in the hidden element is sent to the server with the rest of the form when it is submitted. The fileupload element allows the user to upload files to the server through a Web form interface.

Hidden Elements The hidden form element works nearly the same way as does the single-line text field. The only difference is that the user cannot see or directly modify the value of the hidden element. The most common uses of the hidden element include passing information to the server about product identification numbers, cookie contents, or environmental variables such as the referring page or browser type. A hidden element can be written like this:

Here’s a description of the attributes available for the hidden element: § name. Use this attribute to give the hidden element a unique identifier. This is the first part of the name-value pair that is posted to the server when the form is submitted. § id. This attribute can be used by CSS to reference this element. § value. This attribute represents the information inside the hidden element. This information is attached to the name attribute and sent to the server when the form is posted. Because the hidden element is not visible to the user you don’t have to assign style attributes, and the hidden element has no event attributes. You might expect the onChange attribute to work, but to date no browser supports the onChange event for the hidden element. However, you can modify the value of the hidden element using JavaScript just as you would with a text box.

hidden-form.html

Hidden Element Form



This is an option This is another option Yet another option The final option ———————————————





Fileupload Elements Some server-browser combinations allow the user to upload a file to the server through a Web form. This is accomplished using the fileupload element. Common uses for the fileupload element include submitting photos, lesson assignments, or multimedia files. The fileupload element can only be used with forms that are assigned the “post” method and the "multipart/form-data" enctype. The fileupload element can be written as:

This element has a number of attributes: § name. Use this attribute to give the fileupload element a unique identifier. This is the first part of the name-value pair that is posted to the server when the form is submitted. § id. This attribute can be used by CSS to reference this element. § title. This text can be used for context-sensitive help, tool tips, or as accessibility instructions for auditory browsers. § size. This attribute determines the width, in text characters, of the text box included with the fileupload element. Because the width and height are affected by font size and type, different browsers and users may see differently-shaped text fields even when the size is expressly set. Additionally, IE offers a number of browser-specific attributes designed to improve usability, such as notab, tabindex, and accesskey. These attributes and the crossbrowser JavaScript alternatives are discussed in Project 1. A fileupload element can also accept style attributes such as class and style, and the standard event attributes such as onClick, onMouseOver, and onMouseOut. Additionally, three other event attributes are available: onFocus, onBlur, and onChange. onFocus is fired when the insertion point is moved inside the fileupload element. onBlur is fired when the insertion point is moved out of the fileupload element. onChange fires when the user changes the text (value) of the fileupload field.

The value attribute of the fileupload element contains the path to the file on the client system. For security reasons the value attribute is read-only. This prevents Web sites from uploading users’ files without their knowledge or consent. Only the user can change the value of the fileupload element, by clicking the associated button and selecting the file. The following file demonstrates the read-only value property of the fileupload element.

file-form.html

File Element Form






Note

Two additional form elements are available. has been deprecated in favor of the more versatile . , a more customizable version of the control elements described in this chapter, is new to the HTML specification and so far is available in only a few browsers. For these reasons, and because most of the effects can be duplicated using other HTML tags, using these form elements is not recommended at this time.

Form Layout As you learned in Chapter 2, proper layout of any interface can greatly improve its usability. The following section describes a number of the layout methods available to the Web form designer. Each of these methods includes an example of the layout using a form template. This template is a moderately sized registration form for a Linux information Web site. By comparing the resulting pages you can get an idea of the appearance of each layout type. In the final analysis, though, the best solution for your Web forms may be a combination of two or more of these techniques. Unformatted Forms Unformatted forms use only paragraph tags, horizontal rules, and line breaks to separate form elements. Only the simplest forms should be left unformatted. Besides being aesthetically less pleasing, unformatted forms tend to be long and disorganized. Form elements can only be grouped using vertical spacing and font style. unformatted-layout.html



Unformatted Layout

Register



Name:

E-Mail:

Birthday:

Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec

01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18

19 20 21 22 23 24 25 26 27 28 29 30 31

19

Gender:

 Male   

 Female

Choose a Username and Password:

Username:

Password:

Confirm Password:

Optional Info:

What Linux distribution do you use?

Select One Red Hat Caldera SuSE Corel Slackware Other

How much time do you spend on the Internet each week?

Select one

Under 1 hour 1 to 5 hours 6 to 15 hours 16 to 30 hours Over 30 hours

What is your Internet connection?

Select one 28.8k 33.3k 56k Cable Modem DSL ISDN Satellite T1

What is your favorite Linux Web site?

  I would like to receive your newsletter.

  Check here to receive special offers from our partners.



Advantages of unformatted forms: § Appearance is very similar regardless of browser. § Quick to produce, easy to maintain. § Supported by every form-enabled browser. Disadvantages of unformatted forms: § Long—the user will most likely have to scroll to see the entire form. § Unorganized, so logical relationships between form elements are often not apparent. § Aesthetically displeasing, as sharp alignment of elements is not possible. Recommendation: Use only on short forms. Preformatted Forms Using the PRE tag you can format a form on the page. This style is best used for short forms that do not have to match the surrounding page’s style. The advantage to this method is its simplicity, but that can also be its drawback. Preformatted forms are very limited in structure and style, as only monospace fonts can be used.

preformatted-layout.html

Preformatted Layout

Register



Name: maxlength="50">

Over 30 hours

What is your Internet connection? Select one 28.8k 33.3k 56k Cable Modem DSL ISDN Satellite T1

What is your favorite Linux Web site? Over 30 hours

What is your Internet connection?

Select one 28.8k 33.3k 56k Cable Modem DSL ISDN

Satellite T1

What is your favorite Linux Web site?



Advantages of table formatted forms: § Appearance can be more directly controlled. § Takes advantage of screen space, making multicolumn layout possible. § Organized, so logical relationships are easy to convey using cell colors. § Supported by the most common form-enabled browsers. Disadvantages of table formatted forms: § Can be difficult to code. § Appearance may vary slightly from browser to browser. § Some very old browsers do not support tables. Recommendation: Use on medium-to-long forms if browser compatibility is not an issue. Layer Formatted Forms Formatting a Web form using layers can produce many of the same effects you get using tables—including multicolumn display and color use—while taking up less file space and client processor power. You can use JavaScript or CSS to create layers and then position them precisely on the page. The downside to using layers is that browser support is problematic. Older browsers do not support layers at all, and some newer browsers only support a few layer attributes. Even browsers that support similar attributes can implement them in different ways. It is very important when using layers to thoroughly test the final page on all the browsers that your visitors may be using. Because of this, layer formatted forms are best used on intranets or extranets where the end user’s browser and platform can be controlled. layer-layout.html



Layer Layout



Register

Name:


E-Mail:


Birthday:

Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec

01 02 03 04 05 06 07 08 09 10

11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

19
Gender:

 Male   

 Female

Choose a Username and Password:

Username:
Password:


Confirm Password:



  I would like to receive your newsletter.



  Check here to receive special offers from our partners.



Optional Info:

What Linux distribution do you use?


Select One Red Hat Caldera SuSE Corel Slackware Other

How much time do you spend on the Internet each week?


Select one Under 1 hour 1 to 5 hours 6 to 15 hours 16 to 30 hours Over 30 hours

What is your Internet connection?


Select one 28.8k 33.3k 56k Cable Modem DSL ISDN Satellite

T1

What is your favorite Linux Web site?






Advantages of layer formatted forms: § Appearance can be directly controlled. § Takes advantage of screen space, as multicolumn layout is possible. § Organized; logical relationships are easy to convey using layer colors. § Allows for DHTML animation. § Small file size; less client processing required. Disadvantages of layer formatted forms: § Can be extremely difficult to code properly. § Appearance varies from browser to browser. § Extensive layout testing required, as layers often require workarounds. § Many browsers do not support layers; layers tend to degrade very badly.: Recommendation: Use only on forms where you know the browser type of the end user and plan to use DHTML to animate form elements; otherwise they are rarely worth the effort. Caution The Netscape browser is extraordinarily particular about combining layers with forms. Nested layers will often produce unusual effects or even drop form elements from the page completely. This is another reason I recommend using layer formatted forms only for Web pages that can restrict the end user to a specific browser.

JavaScript and Web Forms

Chapter 4: The “dynamic” part of Dynamic Web Forms comes from JavaScript. Sure, you could post the form every time the user presses a button, then produce pages and pages of serverside script that respond with new HTML for each situation, but you still wouldn’t come close to the flexibility, speed, and power of client-side JavaScript. The key to increasing the functionality and usability of your Web forms is to respond to user input quickly and without interrupting the workflow. This can only be done on the client side and the only real choice for client-side scripting is JavaScript.

A JavaScript Short Course Teaching all of JavaScript would take far more than a single chapter. The intent here is not to explain the entire scripting language but to leverage your existing programming skills toward learning JavaScript. All the basics are covered here, including control structures, array handling, and string manipulation. You should come away with enough knowledge of JavaScript to be able to understand the more complex scripting in the projects. Before you learn JavaScript, you should understand a little about how it works. All clientside scripts are either included within the HTML sent to the browser or in an exterior file

that is referenced from the page. Modern browsers have a utility called a scripting engine that recognizes this script and parses the commands at run time. The JavaScript scripting engine is included with all the latest releases of the most popular browsers—Opera, iCab, Netscape, Internet Explorer, WebTV, and Hot Java, among others. Each scripting engine interprets only a defined set of commands and no others. This makes JavaScript great for those concerned about security—it is impossible to cause a JavaScript code run inside a Web browser to act as a virus or other destructive entity. It also makes JavaScript a headache for Web developers. You’re limited in the functionality of your script based on the complexity of the users’ JavaScript scripting engines. Another hair-puller is that not all JavaScript scripting engines are created equal. While some engines attempt to match up to the standards defined by the World Wide Web Consortium, most fall woefully short. Scripting engines are littered with proprietary commands, quirky implementation, and just plain gaps. As a JavaScript developer you must try to work around these differences. My advice for how to do this: practice, test, practice, test, test again, code, test, test again, test yet again, then launch, fix any bugs; repeat as necessary. JavaScript Basics Client -side scripting presents a number of new challenges for a developer experienced in server-side scripts. Most importantly, as a JavaScript programmer, you can’t control (or even know with any certainty) the operating environment of the client. Your code will have to take this into account and you will need to plan for any number of contingencies. This also means the testing phase is far more in-depth than with server-side scripting. JavaScript programmers should test their code on multiple browsers and operating systems. Developers familiar with other scripting languages such as PHP or VBScript will find many similarities with JavaScript. The basics for any scripting language are all present in JavaScript: variables, operators, arrays, control structures, and functions. For the experienced scripter it is just a matter of learning the new format and nomenclature. If you are unfamiliar with scripting languages or desire more in-depth coverage, see Appendix C for a listing of recommended JavaScript references.

Adding JavaScript to a Web Page You have three ways to insert JavaScript into a Web page. The most direct (and common) way is to use the SCRIPT tag. This HTML tag either brackets the script on the page or references a separate JavaScript file. Although many client-side programmers prefer to place the code on the same page as the HTML for quick access and simplicity, referencing external files is often your best option. Chapter 6 will discuss this option in depth and explain my reasoning. SCRIPT tags can be located anywhere in the document, but the typical placement is in the head or between the HEAD and BODY tags. JavaScript that needs to write to the document, however, should be inside the BODY tags. The basic format of the SCRIPT tag that references an external document is

The format of a SCRIPT tag that holds JavaScript on the page is

The SCRIPT tag has three attributes:

language. This tells the browser which client -side scripting language is being used. Any given browser may have more than one scripting engine—Internet Explorer, for example, includes scripting engines for VBScript and JScript. Browsers without a JavaScript scripting engine will ignore the SCRIPT tag. § src. Only used for SCRIPT tags that reference a separate file, the src attribute gives the name and location (relative or absolute) of the external JavaScript file. This file is usually given the .jss or .js extension, but it isn’t required. § type. The type attribute sets the MIME type of the JavaScript. It is mandatory only when referencing an external file, but can also be used as a supplement to the language attribute. The second way of inserting JavaScript is through event attributes of HTML tags. You might remember seeing this inline technique in the last chapter. The most common use of inline scripting is to reference a JavaScript function located inside a SCRIPT tag, but entire multifunction scripts can be included. I recommend, however, that you keep your inline scripts small. When you need to make a change to your code, long inline scripts can be difficult to find and confusing to edit. Inline scripts are written like this: §

Event attributes associated with forms include the following: § onBlur. This event activates when the focus moves from the attached object to another. For form elements this means that the insertion point has moved to another element. § onChange. Fires when the content of an object is changed and the focus is moved from the attached object. Changing form elements can mean typing new text in a text input element, selecting a new option in a selector, or changing the referred file in a fileupload element. § onClick. This event occurs when the mouse button is pressed while the mouse pointer is over the attached object. The most common use of this event with Web forms is to assign a JavaScript function to a control element. § onDblClick. This event activates when the user quickly presses the mouse button twice while the mouse pointer is over the attached object. The speed of the double-click depends on the operating system and browser. § onFocus. Fires when the insertion point is moved to the attached object. § onMouseOver. Activates when the mouse pointer is moved over the attached object. This event can be assigned to any of the visible form elements. § onMouseOut. This event fires when the mouse pointer is moved away from the attached object. § onReset. Only assigned to the FORM tag, this event activates when the Web form receives a request to reset the form. This event occurs before the information is returned to the starting values. § onSubmit. Another event only assigned to the FORM tag, this event fires when the form receives the submit command. The onSubmit event runs before the form information is sent to the server. The final way to include JavaScript on a Web page is to include the script in the href attribute of an anchor tag. The script runs when the user clicks on the text associated with the link. You might ask why this would ever be used—after all, you can assign an onClick event to an anchor tag. The difference is that the onClick event does not prevent the browser from following the link included in the href attribute. This can cause the page to change or at the very least refresh, something not always desired with online forms. Including the JavaScript in the href attribute prevents this.

Bookmarklets Bookmarklets let you bookmark the JavaScript associated with an anchor tag just like with any other link. Common uses for bookmarklets include resizing your browser, navigating to pages in the browser’s history, or changing the appearance of the page. For more information about bookmarklets visit http://www.book marklets.com/.

You can add JavaScript to an anchor tag like this: Click me

Commenting and Escaping JavaScript Commenting JavaScript involves including text that is not processed by the scripting engine; the sole purpose is to leave a message to those vi ewing your script. Chapter 2 covered the importance of commenting code: proper commenting produces a far cleaner, smoother, and simpler development environment. Of course, the degree of commenting is left up to you and your development team. JavaScript provides a number of ways to comment your code. To comment a single line of code use double slashes (//) at the beginning of the comment. This will cause the browser to ignore everything that follows until it reaches a carriage return. This is the most common type of JavaScript commenting and can be written as: var strVariable = 'Welcome!'; // sets the variable to the welcome message document.write(strVariable); // displays the welcome message An alternative to the double slashes is the opening bracket of an HTML comment

Greater than

3 > 1

true


=

Greater than or equal to

5 >= 2

true