In this section we will shed the light on some important properties and methods provided by the DOM API that will help us working with forms using JavaScript.
The HTMLFormElement
interface represents a <form>
element in the DOM.
This interface inherit properties from HTMLElement
as well as other specific ones.
HTMLFormElement.elements
returns a collection holding all form controls in this form. Check what form controls mean belowHTMLFormElement.length
returns the length of all form controls in this form.
Some elements are omitted for simplicity
button
fieldset
input
select
textarea
This is the preferred way to get the important form elements when working with forms.
This interface inherit properties from HTMLElement
as well as other specific ones.
-
checkValidity()
-
reportValidity()
-
requestSubmit()
-
reset()
Resets the form to its initial state. Check the note below about how the initial state is defined.
-
submit()
Submits the form to the server.
The form initial state is defined in the HTML attributes rather than the DOM properties. It differs according to the type of element.
<input>
(types other thancheckbox
andradio
) is defined by thevalue
attribute.<textarea>
is defined by the inner text written within the starting and closing tags.<select>
is defined by theoption
tags that has theselected
attribute.
formdata
fires every time we callnew FormData()
on a<form>
. It can be used to construct data and submit it asynchronously. 💣 This is relatively a new event and it's not supported in Safari yet.reset
fires when the form is reset.submit
fires when the form is being submitted. Usually authors attach listeners to it and stop the submission to manipulate data, submit the form asynchronously or do many other things