↑
Main Page
Accessing form fields
Accessing form fields
Every form field, whether it is a button, text box, or other, is contained in the form’s
elements
collec-
tion. You can access the various fields in the collection by using their
name
attributes or their positions
in the collection:
var oFirstField = oForm.elements[0]; //get the first form field
var oTextbox1 = oForm.elements[“textbox1”];//get the field with the name “textbox1”
In the shorthand version for accessing an element by its name, every form field becomes a property of
the form itself and can be accessed directly by using its
name
:
var oTextbox1 = oForm.textbox1; //get the field with the name “textbox1”
If the name has a space in it, use bracket notation instead:
var oTextbox1 = oForm[“text box 1”]; //get the field with the name “text box 1”
Form field commonalities
All form fields (except for hidden fields) contain common properties, methods, and events:
?
The
disabled
property is used both to indicate whether the control is disabled as well as to
actually disable the control (a disabled control doesn’t allow any user input, but gives no visual
indication that the control is disabled).
?
The
form
property is a pointer back to the form of which the field is a part.
?
The
blur()
method causes the form field to lose focus (by shifting the focus elsewhere).
?
The
focus()
method causes the form field to gain focus (the control is selected for keyboard
interaction).
?
The
blur
event occurs when the field loses focus; the
onblur
event handler is then executed.
?
The
focus
event occurs when the field gains focus; the
onfocus
event handler is then executed.
For example:
var oField1 = oForm.elements[0];
var oField2 = oForm.elements[1];
//set the first field to be disabled
oField1.disabled = true;
//set the focus to the second field
oField2.focus();
Of course, you can still use
document.getElementById()
with a form field’s ID to
retrieve it directly. The methods discussed in this section are most useful when you
need to iterate over all the fields in a single form.
338
Chapter 11
14_579088 ch11.qxd 3/28/05 11:40 AM Page 338
Free JavaScript Editor
Ajax Editor
©
→