Forms and form Elements

19 305 0
Forms and form Elements

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Chap s and F Elements As we've seen in examples throughout thi use almost all JavaScript programs. This chapter explains th programming with forms in JavaScript. It is assumed that you are already so creation of H s and with the inp ents tha want to refer to a good book on HTML. [1] ter 15. Form orm s book, the of HTML forms is basic to e details of mewhat familiar with the t they contain. If not, you mayTML form ut elem ent-side lists the HTML syntax along with the JavaScript syntax m elements; you may find these useful for quick reference. [1] Such as HTML: T usciano and Bill Kennedy (O'Reilly If you are already familiar with server-side programmin ay find that things are done differently when forms are used with JavaScript. In the server- side model, a it contains is subm once. The emphasis is on processing a complete batch o producing a new web page in response. With JavaScript different. In phasis is not on form submission and processing but instead on event handling. A form and all input elem that JavaScript can use to respond to user interactions w on a checkbox, for example, a JavaScript program can re event handler and m e value of the form. With server- L form isn't useful u unless it has only a single ield and allows the as a shortcut for subm Submit button is never necessary (unless the JavaScript program is working wit program, of cript, a form can have any number of push buttons with event handle number of actions when clicked. In previous chapters, The cli reference section of this book for forms and for he Definitive Guide, by Chuck M ). g using HTML forms, you m itted to the web server all at f input data and dynamically form with the input data , the programming model is quite JavaScript programs, the em ents in it have event handlers ithin the form. If the user clicks ceive notification through an displayed in some other elementight respond by changing th side programs, an HTM text input f nless it has a Submit button (or user to press the Return key ission). With JavaScript, on the other hand, a course). With JavaS rs that perform any h a cooperating server-side we've seen some of the possible actions that such buttons can trigger: replacing one image with another, using lay a new web page, opening a new browser window, and dynamically generating a new HTML document in an ndow or f in hapter, a can even trigger a form itted. As we've see t this book, event h a central element of any interesting JavaScript program. A event handlers (excluding the event handlers of the Link forms or form his chapter introduces the Jav object and the various JavaScript objects that represent form elements. It concludes with an example that illustrates how you can use JavaScript to validate user input on the client before ar ts of the form. cument. So ent nce. The action , properties correspond directly to the action, encoding, es of the <form> tag. These properties and attributes are all they are therefore useful only when the form is actually submitted to a server- r the location property to load and disp other wi rame. As we'll see later to be subm this c JavaScript event handler n in examples throughou andlers are lmost always the nd the most commonly used object) are those used with aScript Form elements. T submitting it to a server-side program running on the web server. 15.1 The Form Object The JavaScript Form object represents an HTML form. Forms are always found as elements of the forms[] array, which is a property of the Document object. Forms appe in this array in the order in which they appear within the document. Thus, document.forms[0] refers to the first form in a document. You can refer to the last form in a document with the following: document.forms[document.forms.length-1] The most interesting property of the Form object is the elements[] array, which contains JavaScript objects (of various types) that represent the various input elemen Again, elements appear in this array in the same order they appear in the do you can refer to the third element of the second form in the document of the curr window like this: document.forms[1].elements[2] The remaining properties of the Form object are of less importa , method, and targetencoding method, and target attribut used to control how form data is submitted to the web server and where the results are displayed; side program. See the client-side reference section for an explanation of the properties, o see a book on HTML or CGI programming [2] for a thorough discussion of the attributes. What is worth noting here is that these Form properties are all rea JavaScript program can dynamically set their values in order to change the way the form d/write strings, so a is submitted. [2] Such as CGI Programming on the World Wide Web, by Shishir Gundavaram (O'Reilly). In the days before JavaScript, a form was submitted with a special-purpose Submit ecial-purpose Reset button. The ) and (as of JavaScript 1.1) reset( ) e. Invoking the submit( ) method of a Form resets the form elements. t provides the avaScript 1.1) the onreset d just before the form avoid it ine click on a Submit button. Calling the submit( ) the onsubmit handler. Th event handler is similar to the handler. It is invoked just before false. This allows a JavaScript program to ask for confirmation of the reset, which can be a good idea when the form is long or detailed. You might request this sort of confirmation with an event handler like the following: <form . onreset="return confirm('Really erase ALL data and start over?')" > Like the onsubmit handler, onreset is triggered only by a genuine Reset button. Calling ) method of a form does not trigger onreset. ects with which we create graphical user interfaces for our JavaScript programs. Figure 15-1 button, and form elements had their values reset with a sp JavaScript Form object supports two methods, submit( , that serve the same purpos submits the form, and invoking reset( ) To accompany the submit( ) and reset( ) methods, the Form objec onsubmit event handler to detect form submission and (as of J event handler to detect form resets. The onsubmit handler is invoke is submitted; it can cancel the submission by returning false. This provides an to check the user's input for errors in order toopportunity for a JavaScript program submitting incomplete or invalid data over the network to a server-side program. We'll see an example of such error checking at the end of this chapter. Note that the onsubm handler is triggered only by a genu form does not triggermethod of a e onreset onsubmit the form is reset, and it can prevent the form elements from being reset by returning the reset( 15.2 Defining Form Elements HTML form elements are the primitive obj shows a complex form that contains at least one of each of the basic form elements. In case you are not already familiar with each type ofHTML form elements, the figure includes a numbered key identifying ample 15-1element. We'll conclude this section with an example (Ex ) that shows the 5-1HTML and JavaScript code used to create the form pictured in Figure 1 and to hook up event handlers to each of the form elements. Figure 15-1. HTML form elements Table 15-1 lists the types of form elements that are availa ipt programmers. The first column of the table nam ble to HTML designers and es the type of form element, s en, each Form object has an elements[] array that contains the objects that m another. By examining the type property of an unknown form element, JavaScript code can determine the type of the element and this done in Example 15-2 JavaScr the second column shows the HTML tags that are used to define elements of that type, third column lists the value of the type property for each type of element. Aand the 've sewe represent the form's elements. Each of these elements has a type property that can be used to distinguish one type of element fro figure out what it can do with that element. (We'll see , at the ble provides a short description of each element and also lists the most important or most commonly used event handler for the various types of elements are available in the client-side reference section, under the name listed in the first column of Table 15-1 end of the chapter.) Finally, the fourth column of the ta that element type. We'll talk more about form elements later in this chapter. Complete details about . Although each type of form element has a separate reference page, note that most of the elements are created with HTML <input> tags and are, in fact, all Input objects. The client-side reference page named "Input" lists the features that all these elements have in common, and the type-specific pages provide specific details about working with a particular type of form element. Note that the names Button, Checkbox, and so on from the first column of the table may not correspond to any actual object in a client-side JavaScript implementation, and note also that the DOM standard does not define any interfaces with these names. Still, each type of form element has a distinct appearance and distinct behavior, and it is useful to treat them as separate types, at least for the purposes of the client-side reference section. In the DOM reference section you can find material about forms and their elements under the names "HTMLFormElement," "HTMLInputElement," "HTMLTextAreaElement," "HTMLSelectElement," and "HTMLOptionElement." Table 15-1. HTML form elements Object HTML tag type property Description and events Button "button"> or <button "button" A push button; onclick. <input type= type="button"> Checkbox <input type="checkbox"> "checkbox" A toggle button without radio- button behavior; onclick. FileUpload <input type="file"> "file" An input field for entering the name of a file to upload to the web server; onchange. Hidden <input type="hidden"> "hidden" not visible to the user; no event handlers. Data submitted with the form but Option <option> none A single item within a Select object; event handlers are on the Select object, not on individu Option objects. al Password <input type="password"> "password" An input field for password entry -- typed characters are not visible; onchange. Radio <input type="radio"> "radio" tton with radio- button behavior -- only one selected at a time; onclick. A toggle bu Reset <input type="reset"> or "reset" A push button that resets a form; <button type="reset"> onclick . Select <select> "select-one" A list or drop-down menu fro which one item may be selec m ted; onchange. (See also Option object.) Select <select multiple> "select- multiple" A list from which multiple items may be selected; onchange. (See also Option object.) Submit or "submit" its a form; onclick. <input type="submit"> A push button that subm <button type="submit"> Table 15-1. HTML form elements Object HTML tag type property Description and events Text <input type="text"> "text" A single-line text entry field; onchange. Textarea <textarea> "textarea" A multiline text entry field; onchange. Now th used to at we've taken a look at the various types of form element and the HTML tags create them, Example 15-1 shows the HTML code used to create the form shown in Figure 15-1. Although the example consists primarily of HTML, it also contains JavaScript code used to define event handlers for each of the form elements. You'll notice event handlers are not defined as HTML attributes. Instead, they are JavaScript ns assigned to the properties of the objects in the form's elements[] array. The event h he various form elem know to understand what the report( ) function is doing. ple 15-1. An HTML form containing all form elements <form name="everything"> <!-- A one-of-everything HTML form . --> <table border="border" cellpadding="5"> <!-- in a big HTML table --> <tr> <td>Username:<br>[1]<input type="text" name="username" size="15"></td> <td>Password:<br>[2]<input type="password" name="password" size="15"></td> <td rowspan="4">Input Events[3]<br> <textarea name="textarea" rows="20" cols="28"></textarea></td> <td rowspan="4" align="center" valign="center"> [9]<input type="button" value="Clear" name="clearbutton"><br> [10]<input type="submit" name="submitbutton" value="Submit"><br> [11]<input type="reset" name="resetbutton" value="Reset"></td></tr> <tr> <td colspan="2"> Filename: [4]<input type="file" name="file" size="15"></td></tr> <tr> <td>My Computer Peripherals:<br> [5]<input type="checkbox" name="peripherals" value="modem">56K ue="tape">Tape Backup</td> <td>My Web Browser:<br> [6]<input type="radio" name="browser" value="nn">Netscape<br> that the functio andlers all call the function report( ), which contains code that works with t ents. The next section of this chapter explains everything you need to Exam Modem<br> [5]<input type="checkbox" name="peripherals" value="printer">Printer<br> [5]<input type="checkbox" name="peripherals" val [6] Explorer< <input type="radio" name="browser" value="ie">Internet br> value= <tr <td>My Hobbies:[7]<br> <select multiple="multiple" name="hobbies" size="4"> ption value="programming">Hacking JavaScript option value="surfing">Surfing the Web <option value="caffeine">Drinking Coffee < </table> </form> ="center"> <!-- Another table--the key to the one above --> <table border="4" bgcolor="pink" cellspacing="1" cellpadding="4"> <tr> <td align="center"><b>Form Elements</b></td> d>[4] FileUpload</td> <td>[5] Checkbox</td></tr> <td>[6] Radio</td> <td>[7] Select (list)</td> <td>[8] Select (menu)</td> <td>[9] Button</td> <td>[10] Submit</td> <td>[11] Reset</td></tr> </table> </div> <script> // This generic function appends details of an event to the big Textarea // element in the form above. It is called from various event handlers. function report(element, event) { var elmtname = element.name; if ((element.type == "select-one") || (element.type == "select- multiple")){ value = " "; for(var i = 0; i < element.options.length; i++) if (element.options[i].selected) value += element.options[i].value + " "; } else if (element.type == "textarea") value = " ."; else value = element.value; var msg = event + ": " + elmtname + ' (' + value + ')\n'; var t = element.form.textarea; t.value = t.value + msg; } // This function adds a bunch of event handlers to every element in a form. [6]<input type="radio" name="browser" "other">Other</td></tr> > <o < <option value="annoying">Annoying my Friends </select></td> td align="center" valign="center">My Favorite Color:<br>[8] <select name="color"> <option value="red">Red <option value="green">Green <option value="blue">Blue <option value="white">White <option value="violet">Violet <option value="peach">Peach </select></td></tr> <div align <td>[1] Text</td> <td>[2] Password</td> <td>[3] Textarea</td> <t <tr> // It doesn't bother checking to see if the element supports the event handler, // it just adds them all. Note that the event handlers call report( ) above. // Note that we're defining event handlers by assigning functions to the // properties of JavaScript objects rather than by assigning strings to // the attributes of HTML elements. function addhandlers(f) { // Loop through all the elements in the form for(var i = 0; i < f.elements.length; i++) { var e = f.elements[i]; e.onclick = function( ) { report(this, 'Click'); } e.onchange = function( ) { report(this, 'Change'); } e.onfocus = function( ) { report(this, 'Focus'); } e.onblur = function( ) { report(this, 'Blur'); } e.onselect = function( ) { report(this, 'Select'); } } // Define some special-case event handlers for the three buttons: f.clearbutton.onclick = function( ) { this.form.textarea.value=''; report(this,'Click'); } f.submitbutton.onclick = function ( ) { report(this, 'Click'); return false; } f.resetbutton.onclick = function( ) { this.form.reset( ); report(this, 'Click'); return false; } } // Finally, activate our form by adding all possible event handlers! Every form element has a name attribute that must be set in its HTML tag if the form is to be submitted to a server-side program. While form submission is not generally of interest g , addhandlers(document.everything); </script> 15.3 Scripting Form Elements The previous section listed the form elements provided by HTML and explained how to embed these elements in your HTML documents. This section takes the next step and shows you how you can work with those elements in your JavaScript programs. 15.3.1 Naming Forms and Form Elements to JavaScript programs, there is another useful reason to specify this name attribute, as you'll see shortly. The <form> tag itself also has a name attribute that you can set. This attribute has nothin to do with form submission. It exists for the convenience of JavaScript programmers. If the name attribute is defined in a <form> tag, when the Form object is created for that form, it is stored as an element in the forms[] array of the Document object, as usual and it is also stored in its own personal property of the Document object. The name of this newly defined property is the value of the name attribute. In Example 15-1, for instance, we defined a form with a tag like this: <form name="everything"> This allowed us to refer to the Form object as: document.everything Often, you'll find this more convenient than the array notation: document.forms[0] Furthermore, using a form name makes your code position-independent: it works even if the document is rearranged so that forms appear in a different order. <img>, <applet>, and other HTML tags also have name attributes that work the same as the name attribute of <form>. With forms, however, this style of naming goes a step further, because all elements contained within a form also have name attributes. When you give a form element a name, you create a new property of the Form object that refers With reasonably chosen names, this syntax is much more elegant than the alternative, which relies on hardcoded (and position-dependent) array indices: document.forms[1].elements[4] In order for a group of Radio elements in an HTML form to exhibit mutually exclusive "radio-button" behavior, they must all be given the same name. In Example 15-1 to that element. The name of this property is the value of the attribute. Thus, you can refer to an element named "zipcode" in a form named "address" as: document.address.zipcode , for instance, we define three Radio elements that all have a name attribute of "browser". Although it is not strictly necessary, it is also common practice to define related groups of Checkbox elements with the same name attribute. Sharing a name attribute like this works naturally for server-side programming, but it is a little awkward on the client side. The solution is straightforward, though: when more than one element in a form has the same name attribute, JavaScript simply places those elements into an array with the specified name. The elements of the array are in the same order as they appear in the document. So, the Radio objects in Example 15-1 can be referred to as: document.everything.browser[0] document.everything.browser[1] document.everything.browser[2] 15.3.2 Form Element Properties All (or most) form elements have the following properties in common. Some elements have other special-purpose properties that are described later, when we consider the various types of form elements individually. type A read-only string that identifies the type of the form element. The third column of Table 15-1 lists the value of this property for each form element. form A read/write string that specifies the "value" contained or represented by the form element. This is the string that is sent to the web server when the form is submitted, and it is only sometimes of interest to JavaScript programs. For Text and Textarea elements, this property contains the text that the user entered. For Button elements, this property specifies the text displayed within the button, which is something that you might occasionally want to change from a script. For Radio and Checkbox elements, however, the value property is not edited or displayed to the user in any way. It is simply a string set by the HTML value attribute that is passed to the web server when the form is submitted. We'll discuss the value property when we consider the different categories of form elements later in this chapter. 15.3.3 Form Element Event Handlers Most form elements support most of the following event handlers: A read-only reference to the Form object in which this element is contained. name A read-only string specified by the HTML name attribute. value [...]... experiment with form elements and the event handlers they trigger An important thing to know about event handlers is that within the code of an event handler, the this keyword always refers to the document element that triggered the event Since all form elements have a form property that refers to the containing form, the event handlers of a form element can always refer to the Form object as this .form Going... event handler for one form element can refer to a sibling form element named x as this .form. x Note that the four form element event handlers listed in this section are the ones that have particular significance for form elements Form elements also support the various event handlers (such as onmousedown) that are supported by (nearly) all HTML elements See Chapter 19 for a full discussion of events and. .. Hidden elements cannot generate events and have no event handlers The value property allows to you read and write the text associated with a Hidden element, but, in general, Hidden elements are not commonly used in client-side JavaScript programming 15.3.9 Fieldset Elements The HTML 4 standard adds new and tags to the set of elements that can appear within a form In IE 5 and later,... portable, and you should define name attributes for all your form elements and refer to them by name 15.4 Form Verification Example We'll close our discussion of forms with an extended example that demonstrates several of the concepts we've been discussing Example 15-2 shows how you might use the onsubmit event handler of the Form object to perform input validation so that you can notify the user and prevent... within a form In IE 5 and later, placing a in a form causes a corresponding object to be added to the form' s elements[ ] array Fieldset elements are not scriptable in interesting ways like other form elements are, and their objects do not have a type property like other form elements do Therefore, the presence of Fieldset objects in the elements[ ] array seems like a mistaken design decision This... that performs form verification It is invoked // from the onsubmit event handler The handler should return whatever // value this function returns function verify(f) { var msg; var empty_fields = ""; var errors = ""; // Loop through the elements of the form, looking for all Text and // Textarea elements that don't have an "optional" property defined // Then check for fields that are empty and make... sections for more details on these and other event handlers that are supported by all HTML elements 15.3.7 Select and Option Elements The Select element represents a set of options (represented by Option elements) from which the user can select Browsers typically render Select elements in drop-down menus or list boxes The Select element can operate in two very distinct ways, and the value of the type property... clicks the mouse on the element This handler is particularly useful for Button and related form elements onchange Triggered when the user changes the value represented by the element by entering text or selecting an option, for example Button and related elements typically do not support this event handler because they do not have an editable value Note that this handler is not triggered every time the... user changes the value of an element and then moves the input focus to some other form element That is, the invocation of this event handler indicates a completed change onfocus Triggered when the form element receives the input focus onblur Triggered when the form element loses the input focus Example 15-1 shows how you can define these event handlers for form elements The example is designed to report... resetting a form) associated with them Because these elements have default actions, they can be useful even without an onclick event handler On the other hand, because of their default actions, they are more useful for forms that are submitted to a web server than for pure client-side JavaScript programs If the onclick event handler returns false, the default action of these buttons is not performed You . document .forms[ 0] refers to the first form in a document. You can refer to the last form in a document with the following: document .forms[ document .forms. length-1]. 5-1HTML and JavaScript code used to create the form pictured in Figure 1 and to hook up event handlers to each of the form elements. Figure 15-1. HTML form elements

Ngày đăng: 05/10/2013, 12:20

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan