<form>

🔰 HTMLElements

<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"]

<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

Last updated