Using JavaScript to Manage Forms

[ LiB ]

Using JavaScript to Manage Forms

Within the context of an HTML page, a form is created using the <FORM> tags. Within the <FORM> tags, individual form elements such as check boxes or text fields are defined.

You can use the power of forms on your Web pages without using JavaScript. However, JavaScript provides powerful validation capabilities and enables you to interact with visitors as they fill out the forms.

The form Object

The browser creates a form object for every form element defined by <FORM> tags. You can assign a name to each element using the optional NAME="" attribute for each element, or you can use the forms[] array, which contains an index listing of every form element on the page, beginning with an index of 0. In addition, each form contains its own elements[] array that contains an entry for each form element on that particular form. For example, the fourth form element on a form called myForm can be referenced as myForm.elements[3] .

Form Properties and Methods

The form object has a number of properties, many of which are objects in their own right. You can use these properties, listed below, to access and manipulate form contents.

  • action . Created based on the <FORM> tag's ACTION attribute.

  • button . An object that users can click to initiate an action.

  • checkbox . An object that enables users to select or clear an option by clicking on it.

  • elements[] . An array of all the form elements.

  • encoding . Created based on the <FORM> tag's ENCTYPE attribute.

  • fileUpload . An object used to specify a file that can be included as form data.

  • hidden . An object that does not appear on the form but that you can programmatically fill with data.

  • length . A property that specifies the number of elements in the forms[] array.

  • method . Created based on the <FORM> tag's METHOD attribute.

  • name . Created based on the <FORM> tag's NAME attribute.

  • password . An object that masks any text that is typed into it.

  • radio . An object that is organized into a collection of similar objects, only one of which can be selected.

  • reset . A button object that enables you to clear and reset a form to its default values.

  • select . An object that provides a list of selectable options.

  • submit . A button object that enables you to submit the form for processing.

  • target . Created based on the <FORM> tag's TARGET attribute.

  • text . An object used to hold a single line of text.

  • textarea . An object similar to the text object except that it accepts multiple lines of text.

The form object also has several methods that can be applied to it:

  • handleEvent() . Enables you to simulate a specific event on the specified object such as click or dblclick events.

  • reset() . Enables you to clear and reset a form to its default values programmatically.

  • submit() . Enables you to submit a form programmatically for processing.

NOTE

Of the three form methods, only the form handleEvent() method enables you to pass it an argument. For example, handleEvent(click) .

Form Events

In addition to event handlers supplied by individual form elements, the form object provides the following two event handlers:

  • The onReset event handler enables you to execute JavaScript statements or call a function before the form is reset.

  • The onSubmit event handler enables you to execute JavaScript statements or call a function before the form is submitted.

These event handlers enable you to execute commands or call subroutines before performing the reset or submit actions requested by the visitor. As the examples that follow will demonstrate , this provides you with the opportunity to create warning messages that inform the visitor of the consequences of his actions or to validate form contents and assist the visitor in properly filling out the form, while at the same time making sure only valid data is provided.

The following list identifies which events are associated with each form element and can be used as a reference to see what events each form element enables you to use when you are developing your forms:

Event

Form Elements Affected

Click

button, checkbox, radio, reset, submit

Blur

button, checkbox, fileUpload, password, radio, reset, select, submit, text, textarea

Focus

button, checkbox, fileUpload, password, radio, reset, select, submit, text, textarea

Select

fileUpload, password, text, textarea


In the next section, I'll show you how to take advantage of event handlers so that you can trigger validation of user input on your forms.

Other form Related Methods

Most form elements provide a number of methods you can use to work with the elements programmatically. These methods enable you to invoke events without depending on the visitor. For example, you might create a form that includes several text fields and a reset button. In the event that the user decides to click on the reset button and start filling out the form all over again, you could add the focus() method to the reset button's onClick event and assist the visitor by placing the cursor back in the first text field. A list of methods supported by form elements includes:

  • The click() method has the same affect as though the user clicked on the object.

  • The blur() method moves the focus away from the object.

  • The focus() method places the focus on the object.

  • The select() method highlights the text in the form elements that contain text.

Form Validation

The real benefit of using JavaScript with your forms is to validate visitor input. Form validation enables you to ensure that the visitor has filled in all required fields and that valid data has been entered in those fields. When the visitor makes a mistake, you can display alert messages explaining the error and ask the visitor to correct the problem before submitting the form again.

The following example creates a form for a bicycle shop that enables Internet customers to place online orders for new bikes. Customers are given a list of options to choose from and are asked to specify what method of payment they plan to use when they pick up their new bikes.

First, I will show the full example, and then I will break it down and explain it piece by piece:

 <HTML>   <HEAD>     <TITLE>Script 3.35- A form validation example</TITLE>     <SCRIPT LANGUAGE="JavaScript" TYPE="Text/JavaScript">     <!-- Start hiding JavaScript statements       function ValidateOrder() {         if (document.myForm.firstName.value.length < 1) {           window.alert("Missing First name! Please correct");           return;         }         if (document.myForm.lastName.value.length < 1) {           window.alert("Missing Last name! Please correct");            return;         }         if (document.myForm.address.value.length < 1) {           window.alert("Missing Address! Please correct");           return;         }         option_selected = "no";         for (i=0; i < document.myForm.radio_option1.length; i++) {           if (document.myForm.radio_option1[i].checked) {             option_selected = "yes";           }         }         if (option_selected == "no") {           window.alert("Please specify a bike model!");           return;         }         window.alert("Your order looks good. Click on Submit!");       }     // End hiding JavaScript statements -->     </SCRIPT>   </HEAD>   <BODY>     <CENTER>       <H2>Welcome to Jerry's Custom Bike Shop</H2>       <H5>Payment due at pickup</H5>     </CENTER>     <FORM NAME="myForm" METHOD="post" ACTION="cgi-bin/myscript">       <B>First name:</B> <INPUT NAME="firstName" TYPE="text" SIZE="15"          MAXLENGTH="20"><BR>       <B>Last name:</B> <INPUT NAME="lastName" TYPE="text" SIZE="15"         MAXLENGTH="20">       <P><B>Mailing Address:</B> <INPUT NAME="address" TYPE="text"         SIZE="30" MAXLENGTH="50"></P>       <P><B>Select the bike you wish to order:</B></P>       10 Speed Deluxe: <INPUT NAME="radio_option1" TYPE="radio"         VALUE="10Speed"><BR>       15 Speed Racer: <INPUT NAME="radio_option1" TYPE="radio"         VALUE=15Speed"><BR>       <P><B>Additional Comments: (Optional)</B></P>       <TEXTAREA NAME="myTextarea" TYPE="textarea" ROWS="4"         COLS="40"></TEXTAREA>       <P><B>Please specify method of payment:</B>       <SELECT NAME="myList">         <OPTION SELECTED VALUE="check">Personal Check         <OPTION VALUE="creditCard">Credit Card         <OPTION VALUE="moneyOrder">Money Order       </SELECT></P>       <INPUT TYPE="reset" VALUE="Reset Form">       <INPUT TYPE="submit" VALUE="Submit Order" onClick="window.alert('Your' +         ' bike will be ready in 5 days')">       <INPUT TYPE="button" VALUE=Validate Order" onClick="ValidateOrder()">     </FORM>   </BODY> </HTML> 

Start out by examining the contents of the body section of the page. This section begins with two headers and defines the form that will use the post method to send the form's contents to a CGI program named myscript . Because the CGI ACTION attribute does not specify a URL or path , you know that the program must reside in the same location as the example page.

 <FORM NAME="myForm" METHOD="post" ACTION="cgi-bin/myscript"> 

NOTE

CGI stands for Common Gateway Interface . CGI is not a programming language. It is a specification that is used by languages such as PERL to run programs on Web servers. In this example it is assumed that the client-side JavaScript is supposed to pass the form's contents off to a Web server for further processing.

NOTE

TIP

You do not have to have access to the CGI or server-side scripts and programs on a Web server to be able to collect the contents of forms that visitors to your Web site fill out. You can always use e-mail to retrieve the contents of your forms.The trick to making this work is to modify the <FORM> tag as shown here:

 <FORM NAME="myForm" ACTION="mailto:jlf04@yahoo.com" ENCTYPE="text/plain"> 

The ACTION="mailto:jlf04@yahoo.com" attribute setting tells the browser to submit the form's contents in an e-mail message to the e-mail address specified by the mailto : setting.The ENCTYPE="text/plain" attribute sends the text in a plain non-encoded format.

The browser will always require confirmation from the visitor before it will attempt to submit the form's contents in an e-mail message. Once confirmed, the contents of the form are sent to the specified e-mail account as the body of the e-mail message.

Next, three text fields are defined in order to collect the visitor's first name, last name, and address information. The two name fields are 15 characters wide, and each can collect up to 20 characters of information. The address field is 30 characters long and can contain up to 50 characters .

 <INPUT NAME="firstName" TYPE="text" SIZE="15" MAXLENGTH="20"> <INPUT NAME="lastName" TYPE="text" SIZE="15" MAXLENGTH="20"> <INPUT NAME="address" TYPE="text" SIZE="30" MAXLENGTH="50"> 

A pair of radio buttons is then defined and grouped using the group name radio_option1 .

 <INPUT NAME="radio_option1" TYPE="radio" VALUE="10Speed"> <INPUT NAME="radio_option1" TYPE="radio" VALUE=15Speed"> 

The next form element is a textarea . It can contain up to 160 characters of additional information regarding the bicycle order:

 <TEXTAREA NAME="myTextarea" TYPE="textarea" ROWS="4" COLS="40"></TEXTAREA> 

A drop-down list named myList defines three options for payment.

 <SELECT NAME="myList">   <OPTION SELECTED VALUE="check">Personal Check   <OPTION VALUE="creditCard">Credit Card   <OPTION VALUE="moneyOrder">Money Order </SELECT> 

The final form elements are three buttons. The first button is a reset button that clears the form and restores all its default settings. The second button is a submit button. Before submitting the form for processing, the submit button's onClick event handler displays an alert message telling the customer that the selected bike will be ready for pick up in five days. The form is submitted when the customer clicks on OK. The last button enables the customer to validate the order before submitting it. When clicked, this button calls the function ValidateOrder() .

 <INPUT TYPE="reset" VALUE="Reset Form"> <INPUT TYPE="submit" VALUE="Submit Order" onClick="window.alert('Your bike will be    ready in 5 days')"> <INPUT TYPE="button" VALUE=Validate Order" onClick="ValidateOrder()"> 

The ValidateOrder() function consists of a series of if statements that check the value of specific form elements to ensure that they have been properly completed.

The first if statement checks the value of the length property for the form's firstName text field. If this field contains no character information, an alert pop-up dialog box appears, instructing the user to fill in that field. The return statement that follows the alert() statement prevents further processing of the ValidateOrder() function.

 if (document.myForm.firstName.value.length < 1) {   window.alert("Missing First name! Please correct");   return; } 

The next section of the ValidateOrder() function checks to see whether one of the radio options has been selected to specify the kind of bike being ordered. You might have noticed that when the form defined the radio elements, it did not set one of them as the default answer; it is possible that the customer might forget to select one of these two options. To check all the radio elements on the form, a for loop is set up that loops through all radio elements beginning at 0 and incrementing by 1 until all the radio options have been processed . The length property of the radio_option1 object specifies the total number of radio buttons that are a part of the group and provides this upper limit.

For each iteration of the loop, an if statement checks each radio button to see whether its CHECKED property has been set; if it has, a variable named option_selected is set equal to yes . Otherwise, this variable remains set equal to no . After every radio element has been examined, another if statement checks to see whether the value of option_selected was ever set to yes ; if this is not the case, an alert popup dialog box appears, instructing the user to pick one of the radio options. This if statement also ends with a return statement that prevents further processing of the ValidateOrder() function.

 option_selected = "no" for (i=0; i < document.myForm.radio_option1.length; i++) {   if (document.myForm.radio_option1[i].checked) {     option_selected = "yes";   } } if (option_selected == "no") {   window.alert("You must select the bike model that you wish to order! Please correct");   return; } 

The final statement in the ValidateOrder() function is executed only if all of the function's preceding validation logic finds that the form has been correctly filled in. This last statement displays a pop-up dialog box informing the customer that the order is ready for processing.

 alert("Your order looks good. Click on Submit!") 

Figure 3.27 shows what the form looks like when you load the page.

Figure 3.27. An example of validating the contents of a form before allowing it to be submitted for processing

graphic/03fig27.gif


Of course, depending on the customer to initiate the validation of his order might not be the best course of action. Instead, you probably want to execute the ValidateOrder() function automatically when the user clicks on the submit button. You can accomplish this by modifying the <FORM> to include a call to ValidateOrder() using the onSubmit event handler:

 <FORM NAME="myForm" METHOD="post" ACTION="cgi-bin/myscript"   onSubmit="return ValidateOrder();"> 

For this validation technique to work, you also must modify the return statement on all the if statements in the function to say return false , as shown in the following example. This modification not only stops the processing of the ValidateOrder() function as soon as a validation error is discovered , but also prevents the submit event from executing.

 if (document.myForm.firstName.value.length < 1) {   window.alert("Missing First name! Please correct");   return false; } 

Another validation technique you might want to consider is to validate each form element as the customer completes it. To use this technique, you must understand the concepts of focus and blur . When a cursor has been placed in a text field, that field is said to have the document's focus.

Any keystroke that is typed is sent to that field. If you then move the cursor to a different location in the form, the text field loses focus, a situation known as blur . Selecting a form element executes its focus event, and moving the focus to another form element executes the blur event for the form object that has lost focus.

In the following example, the onBlur even handler has been added to an <INPUT> tag that defines a text object. The ValidateOrder() function executes after the customer selects the text field and then changes the form's focus to another object. Of course, if the customer forgets to fill in this field and never selects it, this validation technique will not help.

 <INPUT NAME="firstName" TYPE="text" SIZE="15" MAXLENGTH="20" VALUE=""     onBlur="ValidateOrder()"> 

NOTE

TIP

One validation technique you can use to make things as easy as possible for your users is to add a statement that places the focus on the form object that has not been properly completed. For example, you might modify the if statement that validates the customer's first name as shown here:

 if (document.myForm.firstName.value.length < 1) {   window.alert("Missing First name! Please correct");   document.myForm.firstName.focus(); } 

[ LiB ]


Learn JavaScript In a Weekend
Learn JavaScript In a Weekend, Second Edition
ISBN: 159200086X
EAN: 2147483647
Year: 2003
Pages: 84

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net