<form>

๐Ÿ”ฐ HTML โŸฉ Elements โŸฉ

<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