Form properties and methods
Forms and control elements, such as have a lot of special properties and events. Working with forms will be much more convenient when we learn them.
Navigation: form and elements
Document forms are members of the special collection document.forms. That’s a so-called “named collection”: it’s both named and ordered. We can use both the name or the number in the document to get the form. When we have a form, then any element is available in the named collection form.elements. For instance: There may be multiple elements with the same name. This is typical with radio buttons and checkboxes. In that case, form.elements[name] is a collection. For instance: These navigation properties do not depend on the tag structure. All control elements, no matter how deep they are in the form, are available in form.elements.
Backreference: element.form
For any element, the form is available as element.form. So a form references all elements, and elements reference the form. Here’s the picture: For instance:
Form elements
Let’s talk about form controls.
input and textarea
We can access their value as input.value (string) or input.checked (boolean) for checkboxes and radio buttons. Like this:
select and option
A
new Option
- option.selected
Is the option selected. option.index
The number of the option among the others in its
Text content of the option (seen by the visitor).
References
Specification: https://html.spec.whatwg.org/multipage/forms.html.
Summary
Form navigation: document.forms
- A form is available as document.forms[name/index]. form.elements
- Form elements are available as form.elements[name/index], or can use just form[name/index]. The elements property also works for
- Elements reference their form in the form property. Value is available as input.value, textarea.value, select.value, etc. (For checkboxes and radio buttons, use input.checked to determine whether a value is selected.) For
document.forms.my; // the form with name="my" document.forms[0]; // the first form in the document
Follow the lesson from Microsoft Web-Dev-For-Beginners course