<form>
JS.info ⟩ Form properties and methods ⭐️⭐️
MDN ⟩
HTMLFormElement ⟩ .elements: HTMLFormControlsCollection
NodeList ⟩ RadioNodeList - 由 radio buttons 產生的 collection
NodeList - node.childNodes 或 .querySelectorAll() 回傳的物件
Radio Buttons - <input type="radio>
<label>
By wrapping an input
element inside of a label
element it will automatically associate the radio button input with the label element surrounding it.
access form & elements
⭐️ document forms are members of document.forms
⭐️ form elements are available in form.elements
const {log} = console;
/*
⭐️ document forms are members of `document.forms`
⭐️ form elements are available in `form.elements`
*/
// ⭐️ get <form> by "name"
let form = document.forms.form1; // <form name="form1">
// = document.forms[0]
// ⭐️ get <input> by "name"
let input = form.elements.age; // <input name="age">
log(input.value); // 17
// ⭐️ being radio buttons, `form.elements['sex']` is a collection
let sex = form.elements.sex; // RadioNodeList ⭐️
// ⭐️ value of checked radio button ('' if none checked ⭐️)
log(sex.value) // "female"
// ⭐️ turn collection into array
let values = [...sex].map(input => input.value)
log(values) // ["male","female"]
<form name="form1">
<!-- type="text" -->
<input name="name" value="Joy">
<input name="age" value="17">
<!-- ⭐️ radio buttons with same "name" -->
<input type="radio" name="sex" value="male">
<input type="radio" name="sex" value="female" checked>
</form>
JS.info ⟩ Form properties and methods ⭐️⭐️
codepen ⟩ form & inputs
<fieldset> as "subform"
// ⭐️ form.elements: HTMLFormControlsCollection
log(form.elements.username); // <input name="username">
// ⭐️ fieldset
let fieldset = form.elements.userInfo; // HTMLFieldSetElement
log(fieldset.nodeName) // FIELDSET
// ⭐️ fieldset is a "subform"
// ⭐️ fieldset.elements: HTMLFormControlsCollection
log(fieldset.elements.username === form.elements.username) // true
// ⭐️ shorter notation: form.name
log(form.username === form.elements.username) // true
<form id="form">
<fieldset name="userInfo">
<legend>info</legend>
<input name="username" type="text">
</fieldset>
</form>
Last updated
Was this helpful?