Forms 2

Page section: posts
More on forms

In part 1 we looked at the HTML elements themselves, what they’re for and how they work.

In this part we’ll take a look at the JS side of forms.

Forms are special

Selecting forms

In JS forms are part of an HTML collection called forms and accessed through document.forms. To select a specific form on a page you can do so with either it’s position in the DOM (the first form will be numbered 0), or by using it’s HTML name attribute.

<form name="my-form">
    //
</form>

So if this was the second form on the page in JS you could access it like so:

const myForm = document.forms[1];

or:

const myForm = document.forms['my-form'];

If the name of the form is valid JavaScript (letters, underscores, dollar sign or numbers that aren’t the first character) you can access the form with simple dot notation too:

// if the form has the name 'contact' you can use:
const contactForm = document.forms.contact

Selecting form elements

The elements of a form make up another HTML collection accessed with .elements like so:

document.forms[0].elements

These elements are again accessed through their HTML name attribute or their position in the form.

<form name="login_form">
    <label for="email">email:</label>
    <input name="email" type="email" />
    <label for="password">password:</label>
    <input name="password" type="password" placeholder="Min 12 characters" />
    <i class="far fa-eye" id="toggle-password"></i>
    <button type="submit">Log in</button>
</form>

To select the password field in the above form you can use any of the following:

document.forms[0].elements.password
document.forms.login_form.elements.password

// You can skip the word elements..
document.forms.login_form.password
document.forms['login_form'].password

// assuming the form is the first on the page..
document.forms[0].email
document.forms[0][1]

More..

The following form has two issues. First the radio button inputs all have the same name. This is necessary to form a radio button group where only one of group can be active at one time.

Secondly they’re all contained in a fieldset element.

Choose a payment method:

  1. Hide/Show Password using Eye icon