- Document forms are members of the special collection
document.forms
.
- That’s a named collection: we can use both the name and the number to get the form.
document.forms.my // the form with name="my"
document.forms[0] // the first form in the document
- When we have a form, then any element is available in the named collection
form.elements
.
- There may be multiple elements with the same name, that’s often the case with radio buttons.
- In that case
form.elements[name]
is a collection, for instance.
<form name="my">
<input name="one" value="1">
<input name="two" value="2">
</form>
let form = [document.forms.my](<http://document.forms.my/>);
let elem = form.elements.one; // <input name="one"> element
console.log(elem.value); // 1
let ageElems = form.elements.age;
console.log(ageElems[0].value); // 10, the first input value
- These navigation properties do not depend on the tag structure.
- All elements, no matter how deep they are in the form, are available in form.elements.
<form id="form">
<fieldset name="userFields">
<legend>info</legend>
<input name="login" type="text">
</fieldset>
</form>
alert(form.elements.login); // <input name="login">
let fieldset = form.elements.userFields;
alert(fieldset); // HTMLFieldSetElement
// we can get the input both from the form and from the fieldset
alert(fieldset.elements.login == form.elements.login); // true
- For any element, the form is available as element.form.
- So a form references all elements, and elements reference the form.
<form id="form">
<input type="text" name="login">
</form>
// form -> element
let login = form.login;
// element -> form
alert(login.form); // HTMLFormElement
Form Elements
- Access the value as
input.value
or input.checked
for checkboxes.
- A
<select>
element has 3 important properties:
select.options
– the collection of <option>
elements,
select.value
– the value of the chosen option,
select.selectedIndex
– the number of the selected option.