DOM Forms
In the HTML DOM (Document Object Model), forms are represented as objects that allow JavaScript to access, validate, and manipulate <form>
elements and their inputs dynamically.
The DOM gives developers full control over form data — from reading and updating input values to handling submissions and validation in real time.
Form Element:
The <form>
tag can be accessed using document.forms
, document.getElementById()
, or querySelector()
.
Form Inputs:
Inputs like <input>
, <textarea>
, and <select>
are child elements of a form and can be accessed via the elements
collection.
Form Events:
Common events include submit
(on form submission), input
(when the user types), and change
(after input loses focus).
Accessing Forms
By ID:
The id
attribute uniquely identifies an element on a page. Using JavaScript, you can quickly select this element to read or modify its content, style, or attributes.
const form = document.getElementById("myForm");
By Name:
In JavaScript, “By Name” refers to selecting HTML elements based on their name
attribute using document.getElementsByName()
. It returns all elements that share the specified name
.
const form = document.forms["myForm"];
By Index (if multiple forms exist):
In JavaScript, when multiple elements share the same name
or are part of a collection (like multiple <form>
elements), you can access a specific element using its index in the collection.
const form = document.forms[0];
Accessing Form Inputs
Once you have a reference to a form, there are several ways to access its inputs:
Via elements Collection:
The elements
property of a form gives a collection of all its input elements. You can access an input by its name
or id
.
const input = form.elements["username"]; // Access input by name
By Query Selector:
You can use querySelector
to select inputs inside a form using CSS selectors.
const input = document.querySelector("#myForm input[name='username']");
Getting and Setting Input Value:
Once you have the input element, you can read or modify its value using the .value
property.
const value = form.elements["username"].value; // Get value
form.elements["username"].value = "newValue"; // Set value
Common Form Properties and Methods
Properties
Property | Description |
---|---|
form.elements | Returns all input elements in the form |
element.value | Gets or sets the input’s value |
element.name | The name of the input field |
element.type | Type of the input (text , checkbox , etc.) |
element.checked | Boolean for checkbox/radio (true if checked) |
form.action | Submission URL |
form.method | HTTP method (get or post ) |
Methods
Method | Description |
---|---|
form.submit() | Programmatically submits the form |
form.reset() | Resets form to initial values |
element.focus() | Sets focus on an input |
element.blur() | Removes focus from an input |
Form Events
Submit Event
Triggered when the form is submitted. Use event.preventDefault()
to stop default form submission (page reload) and handle data with JavaScript.
form.addEventListener("submit", (event) => {
event.preventDefault();
const username = form.elements["username"].value;
console.log("Submitted:", username);
});
Input Event (real-time changes)
Fires every time the value changes, useful for live feedback.
const input = form.elements["username"];
input.addEventListener("input", () => {
console.log("Typing:", input.value);
});
Change Event (after focus loss)
Triggered when the user leaves the input field after making a change.
input.addEventListener("change", () => {
console.log("Final value:", input.value);
});
Example — Simple Form with Validation
<!DOCTYPE html>
<html>
<body>
<form id="myForm">
<label>Username: <input type="text" name="username"></label>
<label>Email: <input type="email" name="email"></label>
<button type="submit">Submit</button>
</form>
<script>
const form = document.getElementById("myForm");
// Handle submission
form.addEventListener("submit", (e) => {
e.preventDefault();
const username = form.elements["username"].value;
const email = form.elements["email"].value;
console.log({ username, email });
if (!username) {
alert("Username is required!");
form.elements["username"].focus();
}
});
// Real-time email validation
form.elements["email"].addEventListener("input", (e) => {
e.target.style.border = e.target.value.includes("@")
? "2px solid green"
: "2px solid red";
});
</script>
</body>
</html>
Working with Specific Input Types
Checkboxes / Radio Buttons:
Checkboxes and radio buttons have a checked
property to determine their state.
const checkbox = form.elements["agree"];
console.log(checkbox.checked); // true if checked
checkbox.checked = true; // Programmatically check
Select Dropdowns:
Dropdowns use the value
property for the selected option, and options
+ selectedIndex
for more details.
const select = form.elements["color"];
console.log(select.value); // Selected option value
console.log(select.options[select.selectedIndex].text); // Option text
Looping Through Inputs:
You can iterate over all form elements using the elements
collection.
const inputs = form.elements;
for (const input of inputs) {
console.log(input.name, input.value);
}
Form Validation
HTML5 Validation:
Use attributes like required
, pattern
, min
, and max
.
<input type="email" required
pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,}$">
You can check validity in JavaScript:
if (!form.checkValidity()) {
alert("Please fill out all required fields!");
}
Custom Validation:
if (!form.elements["username"].value.trim()) {
alert("Username cannot be empty!");
return false;
}