As discussed in Chapter 11, "The Document Objects: Forms, Images, and Links," the document object has a forms property. It contains an array of all the forms that have been defined in the document. Each element of the array is a form object and the number in the index of the array represents the order in which the form appeared on the page. The first form would be document.forms[0] . Each form contains elements, also represented as an array. The elements represent the input types of the form, such as a checkbox, radio button, or text field. By naming each of the forms and its respective elements, it is much easier to work with them in JavaScript. (See Chapter 11 for a complete discussion of the forms[] array.) There are a number of events associated with the form's elements. Many of them were also covered in Chapter 11. They are listed in Table 12.6. Table 12.6. Event handlers for the form's elements.
12.6.1 ButtonsOne of the most common GUI form elements is the button. The button object has no default action and is normally used to trigger an event such as the OnClick event. HTML 4 allows you to create a <button> tag without the <input> tag. [3] There are several buttons associated with a form; the buttons are called:
If an event is an attribute of a form tag, then the event occurs when the user presses one of the buttons associated with the form object. 12.6.2 this for Forms and this for ButtonsThe this keyword refers to the current document and is especially helpful when dealing with forms. In forms that contain multiple items, such as checkboxes, radio buttons, and text boxes, it is easier to refer to the item with the this keyword, than by using its full name when calling a function or an event handler. (Examples of the this keyword are shown in Chapter 11.) In a form, this could be the form itself or one of the input devices. With an event handler, the this keyword by itself references the current object, such as an input device, whereas this.form references the form object where the input device was created. Example 12.12<html><head><title>The this keyword</title> <script language="JavaScript"> 1 function display_formval( myform ){ alert("text box value is: " + myform.namestring.value ); } 2 function display_buttonval( mybutton ){ alert("button value is: " + mybutton.value ); } </script> </head> <body><b> <hr> 3 <form name="simple_form"> <p> Type your name here: <input type="text" name="namestring" size="50"> <p> 4 <input type="button" value="Print Form Stuff" 5 onClick="display_formval(this.form);" > <input type="button" value="Print Button Stuff" 6 onClick="display_buttonval(this) ;" > <input type="reset" value="Clear"> </form> </body></html> EXPLANATION
12.6.3 Forms and the onClick Event HandlerThe onClick event handler is used most often in forms. The click event occurs when a button in a form, such as a radio or checkbox, is pressed. It also happens when an option is selected in a Select menu. In Chapter 11, we used many examples of the onClick event handlers. Here are a few more. Example 12.13<html> <head> <title>Event Handling and Forms</title> <script language=javascript> 1 function greetme(message){ alert(message); } </script> </head> <body bgcolor=white> <h2> Greetings Message </h2> <hr> 2 <form> 3 <input type="button" value="Morning" 4 onClick="greetme('Good morning. This is your wakeup call!')"> <input type="button" value="Noon" onClick="greetme('Let\'s do lunch.')"> <input type="button" value="Night" onClick=" greetme('Have a pleasant evening.\nSweet dreams...')"> </form> </body> </html> EXPLANATION
12.6.4 Event Handlers and Event Methods Working TogetherYou'll find that many JavaScript programs use a combination of event handlers and event methods, especially when working with forms. The following example uses event handlers and event methods. It creates a random number between 1 and 10, and asks the user to guess what the number is. As soon as the document is loaded, the onLoad event handler is triggered, and when the user presses the button, the onClick handler is fired up. The focus() method is used to put focus in the text box where the user will enter his guess. Example 12.14<html> <head><title>Event Handling</title> <script language="JavaScript"> var tries=0; 1 function randomize(){ // Random number is set when the document has loaded var now=new Date(); num=(now.getSeconds())%10; // Very cool! num++; } 2 function guessit(form){ // Function is called each time the user clicks the button if (form.tfield.value == num){ alert("Correct!!"); 3 form.tfield.focus(); n=0; randomize(); } else{ tries++; 4 alert(tries + " Wrong. Try again."); form.tfield.value=""; // Clear the text box form.tfield.focus(); // Put the cursor in the text box } } // End hiding from old browsers --> </script> </head> <body bgcolor="lightgreen" 5 onLoad="randomize() "> <!-- Call function when page is loaded- -> <center> <b>Pick a number between 1 and 10</b> <form name="myform"> 6 <input type="textbox" size=4 name="tfield"> <p> 7 <input type="button" name="button1" 8 value="Check my guess" onClick="guessit(this.form) "> </form> </body> </html> This script was modified from one written by Andree Growney available at http://www.htmlgoodies.com/primers/jsp/hgjsp_.html. EXPLANATION
12.6.5 Forms and the onFocus and onBlur Event HandlersThe onFocus event handler is triggered when a form element has focus: the cursor is sitting in the box, waiting for key input or in the case of a button, for the Enter key to be pressed. The onBlur event is triggered when the form element loses focus: when the cursor is moved away from the input device. Example 12.15<html> <head><title>Using the onFocus Event Handler</title> <script language="JavaScript"> 1 function handler(message) { 2 window.status = message; // Watch the status bar } </script> </head> <body bgcolor="magenta"><b>The onFocus Event Handler <i>(When you click in one of the boxes, focus goes to the status bar)</i> 3 <form name="form1"> <p>Type your name: 4 < input type="text" name="namestring" size="50" 5 onFocus="handler('Don\'t forget to enter your name')"> <p>Talk about yourself here:<br> 6 < textarea name="comments" align="left" 7 onFocus="handler('Did you add comments?')" rows="5" cols="50">I was born... </textarea><p> <input type="button" value="submit"> <input type="reset" value="clear"> </form> </body> </html> EXPLANATION
12.6.6 Forms and the onChange Event HandlerThe onChange event handler is triggered after the user modifies the value or contents of an HTML input, select, or text area element in a form, and then releases the mouse. This is another event handler that can be useful in checking or validating user input. Example 12.16<html> <head><title>onChange Event Handler</title> </head> <body> 1 <form> Please enter your grade: 2 <input type="text" onChange=" grade=parseInt(this.value); // Convert to integer 3 if(grade < 0 grade > 100){ alert('Please enter a grade between 0 and 100'); } 4 else{ confirm('Is '+ grade + ' correct?'); } 5 " > 6 </form> </body> </html> EXPLANATION
Figure 12.21. The user enters a value. A change has taken place. The onChange handler is invoked.
12.6.7 Forms and the onSubmit Event HandlerThe onSubmit event handler was discussed in detail in Chapter 11, but it is included again in this chapter since it is such an important form event. You will see this event again in Chapter 13, "Regular Expressions and Pattern Matching." If you recall, the onSubmit event is an attribute of the HTML <form> tag and is triggered when the user presses the submit button after filling out a form. This event allows the programmer to validate the form before sending it off to the server. If the return value from the event handler is true, the form will be submitted; if false it won't be submitted. The following examples demonstrate two different validation programs using an onSubmit event handler. Example 12.17<html><head><title>The onSubmit Event Handler</title></head> <body font="arial" size=3> <script language="JavaScript"> 1 function popUp(){ 2 newWin=window.open('','NewWin','toolbar=no, status=no,width=500,height=200'); 3 newWin.document.write("<h3>Form data</h3>"); newWin.document.write("<b>Your name is:</b> " + document.form1.namestring.value); newWin.document.write("<br><b>Your address is: </b>" + document.form1.address.value); } </script> <b> <hr> 4 <form name="form1" onSubmit="popUp();"> <p> Type your name: 5 <input type="text" name="namestring" size="50"> <p> Type in your address: <input type="text" name="address" size="80"> <p> 6 <input type="submit" value="Submit form"> <input type="reset" value="Clear"> </form></body> </html> EXPLANATION
Example 12.18<html><title>Check it Out!</title> <head> <script language="JavaScript"> // Script modified from original found at // http://javascript.internet.com 1 function okForm(form ){ if (form.accept.checked == true){ return true;} else{ alert("Please check the box!"); form.accept.focus(); return false;} } </script> </head> <body bgcolor="silver"> <font face="arial,helvetica" size=2> <b>Thank you for your order. Check the box to continue.</b> 2 <form action="/cgi-bin/checkout.pl" method="post" 3 onSubmit="return okForm(this)"> <input type="checkbox" name="accept" value="0" > 4 <input type="submit" value="Go to checkout" > <input type="button" value="Go to Home Page" 5 onClick="window.location.replace('../localhost/default.htm');" > </form> </body> </html> EXPLANATION
|