15.3 Scripting Form Elements
15.3.1 Naming Forms and Form Elements
This allowed us to refer to the Form object as:
Often, you'll find this more convenient than the array notation:
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 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:
With reasonably chosen names, this syntax is much more elegant than the alternative, which relies on hardcoded (and position-dependent) array indices:
document.everything.browser document.everything.browser document.everything.browser
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.
15.3.3 Form Element Event Handlers
Example 15-1 shows how you can define these event handlers for form elements. The example is designed to report events as they occur by listing them in a large Textarea element. This makes the example a useful way to 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 a step further, this means that an 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 event handlers.
The Button form element is one of the most commonly used, because it provides a clear visual way to allow the user to trigger some scripted action. The Button object has no default behavior of its own, and it is never useful in a form unless it has an onclick (or other) event handler. The value property of a Button element controls the text that appears within the button itself. In fourth-generation browsers, you can set this property to change the text (plain text only, not HTML) that appears in the button, which can occasionally be a useful thing to do.
Note that hyperlinks provide the same onclick event handler that buttons do, and any button object can be replaced with a link that does the same thing when clicked. Use a button when you want an element that looks like a graphical push button. Use a link when the action to be triggered by the onclick handler can be conceptualized as "following a link."
In HTML 4, you can create Button, Submit, and Reset buttons with the <button> tag instead of the traditional <input> tag. <button> is more flexible, because instead of simply displaying the plain text specified by the value attribute, it displays any HTML content (formatted text and/or images) that appears between <button> and </button>. The Button objects created by a <button> tag are technically different from those created by an <input> tag, but they have the same value for the type field and otherwise behave quite similarly. The main difference is that because the <button> tag doesn't use its value attribute to define the appearance of the button, you can't change that appearance by setting the value property. In this book, we use the terms Button, Submit, and Reset to refer to objects created with either <input> or <button>.
15.3.5 Toggle Buttons
The Checkbox and Radio elements are toggle buttons, or buttons that have two visually distinct states: they can be checked or unchecked. The user can change the state of a toggle button by clicking on it. Radio elements are designed to be used in groups of related elements, all of which have the same value for the HTML name attribute. Radio elements created in this way are mutually exclusive -- when you check one, the one that was previously checked becomes unchecked. Checkboxes are also often used in groups that share a name attribute, and when you refer to these elements by name, you must remember that the object you refer to by name is an array of same-named elements. In Example 15-1, we saw three Checkbox objects with the name "peripherals". In this example, we can refer to an array of these three Checkbox objects as:
To refer to an individual Checkbox element, we must index the array:
document.everything.peripherals // First form element named "peripherals"
Radio and Checkbox elements both define a checked property. This read/write boolean value specifies whether the element is currently checked. The defaultChecked property is a read-only boolean that has the value of the HTML checked attribute; it specifies whether the element was checked when the page was first loaded.
Radio and Checkbox elements do not display any text themselves and are typically displayed with adjacent HTML text (or, in HTML 4, with an associated <label> tag.) This means that setting the value property of a Checkbox or Radio element does not alter the visual appearance of the element, as it does for Button elements. You can set value, but this changes only the string that is sent to the web server when the form is submitted.
15.3.6 Text Fields
Netscape 4 and later and Internet Explorer 4 and later define onkeypress , onkeydown, and onkeyup event handlers (note, however, that they are not yet part of the DOM standard). These handlers can be specified for any Document object, but they are most useful (and, in Netscape 4, only useful) when specified on Text and related form elements that actually accept keyboard input. You may return false from the onkeypress or onkeydown event handlers to prevent the user's keystroke from being recorded. This can be useful, for example, when you want to force the user to enter only digits. See "HTMLElement" in the client-side and DOM reference 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 depends on how it is configured. If the <select> tag has the multiple attribute, the user is allowed to select multiple options, and the type property of the Select object is "select-multiple". Otherwise, if the multiple attribute is not present, only a single item may be selected, and the type property is "select-one".
When the user selects or deselects an option, the Select element triggers its onchange event handler. For "select-one" Select elements, the read/write selectedIndex property specifies by number which one of the options is currently selected. For "select-multiple" elements, the single selectedIndex property is not sufficient to represent the complete set of selected options. In this case, to determine which options are selected you must loop through the elements of the options array and check the value of the selected property for each Option object.
In addition to its selected property, the Option element has a text property that specifies the string of plain text that appears in the Select element for that option. You can set this property to change the text that is displayed to the user. The value property is also a read/write string that specifies the text to be sent to the web server when the form is submitted. Even if you are writing a pure client-side program and your form never gets submitted, the value property (or its corresponding HTML value attribute) can be a useful place to store any data that you'll need if the user selects a particular option. Note that the Option element does not define form-related event handlers; use the onchange handler of the containing Select element instead.
In addition to setting the text property of Option objects, there are other ways you can dynamically change the options displayed in a Select element. You can truncate the array of Option elements by setting options.length to the desired number of options, and you can remove all Option objects by setting options.length to zero. Suppose we have a Select object named "country" in a form named "address". We can remove all options from the element like this:
document.address.country.options.length = 0; // Remove all options
We can remove an individual Option object from the Select element by setting its spot in the options array to null. This deletes the Option object, and any higher elements in the options array automatically get moved down to fill the empty spot:
// Remove a single Option object from the Select element // The Option that was previously at options gets moved to options... document.address.country.options = null;
// Create a new Option object var zaire = new Option("Zaire", // The text property "zaire", // The value property false, // The defaultSelected property false); // The selected property // Display it in a Select element by appending it to the options array: var countries = document.address.country; // Get the Select object countries.options[countries.options.length] = zaire;
In HTML 4, you can use the <optgroup> tag to group related options within a Select element. The <optgroup> tag has a label attribute that specifies text to appear in the Select element. Despite its visual presence, however, an <optgroup> tag is not selectable by the user, and HTMLOptGroupElement objects never appear in the options array of the Select element.
15.3.8 Hidden Elements
15.3.9 Fieldset Elements
The HTML 4 standard adds new <fieldset> and <label> tags to the set of elements that can appear within a form. In IE 5 and later, placing a <fieldset> 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 is particularly true since <label> tags do not cause corresponding objects to be added to the elements array. The Mozilla and Netscape 6 browsers have chosen to follow Microsoft's lead on this in order to be compatible with IE.
What this means is that if you define a form that contains fieldsets, the contents of the elements array differ in recent, HTML 4-capable browsers and in older, pre-HTML 4 browsers. In this situation, using position-based numeric indexes in the elements array is not portable, and you should define name attributes for all your form elements and refer to them by name.