In this article, I'll discuss the foundational aspects of forms in JavaScript.

  1. What is Form?
  2. Form Elements and Properties
  3. Collections in Forms
  4. Focus and Blur Events
  5. Form Events

What is Form?
Forms were originally designed to allow websites to send user-entered information to a server through an HTTP request. However, forms are also part of the DOM, meaning they have properties and events similar to other elements. This allows JavaScript to dynamically control form-related fields, such as inputs, checkboxes, and textareas, enhancing their functionality.

Form Elements and Properties
Some common form elements are , , , checkboxes, and radio buttons.
The values for , , and are of type string.
The values for checkboxes and radio buttons are of type boolean.

We can get the values using a dot notation:
e.g. input.value, input.checked

Collections in Forms
Collections in forms are array-like objects that allow you to access groups of form elements.

  1. document.forms: A collection of all
    elements in a document.
const firstForm = document.forms[0]; // Access the first form
const formWithId = document.forms.myId; // Form with id="myId"
const formWithName = document.forms["myName"]; // Form with name="myName"
  1. form.elements: A collection of all elements inside a specific form.
const inputs = firstForm.elements; // All elements inside the firstForm
const usernameInput = firstForm.elements["username"]; //

Focus and Blur Events
Form elements are the only elements that can be navigated using the keyboard, such as with the Tab key.
Other non-form elements can be made focusable by adding the tabIndex attribute.

Focusing on an element signals readiness for input, which can be a good time to initialize the field or prepare it for interaction.

Losing focus, known as blur, often indicates that the user has finished interacting with the field. At this point, we can execute functions such as storing data, validating input, or triggering other actions.

Form Events
Some form-related events and their use cases:

change Event:
Triggered when a user finishes changing a field, such as after losing focus or clicking elsewhere.

input Event:
Triggered in real-time whenever a value changes, such as when a user types, deletes, or modifies the text.

submit Event:
Triggered when a form is submitted, either by clicking a button or an input with type="submit" or by pressing Enter within a form field.

This time, I covered the foundational aspects of working with forms in JavaScript. I'll delve deeper into this topic by exploring practical applications, such as using FormData and sendBeacon for advanced form handling.