-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
DOM Forms refer to the HTML <form>
elements and their input controls that JavaScript can access and manipulate. Forms are the primary way users interact with web applications, such as submitting login credentials, entering contact details, or filling survey data.
The DOM Forms object represents all forms in a document. By using JavaScript, you can access, validate, modify, or submit forms dynamically, providing a better user experience without requiring page reloads.
Working with DOM Forms is essential because it allows you to:
Access all form elements and their values programmatically.
Validate user input before sending it to the server.
Handle form events like submit, reset, input, and change.
Add or remove form elements dynamically based on user actions.
Control the state of form elements (enable, disable, check, or uncheck).
Forms are the backbone of interactive web applications, and mastering DOM Forms is key to creating responsive, user-friendly sites.
document.forms
CollectionAll forms on a webpage can be accessed using the document.forms
collection, which returns an HTMLCollection of all form elements:
let forms = document.forms;
console.log(forms.length); // Total number of forms
console.log(forms[0]); // First form in the document
Forms can also be accessed directly using their name
or id
attribute:
<form id="loginForm" name="loginForm">
<input type="text" name="username">
<input type="password" name="password">
</form>
let loginFormByName = document.forms["loginForm"]; // Using name
let loginFormById = document.getElementById("loginForm"); // Using ID
Each form contains elements, including inputs, selects, textareas, checkboxes, radios, and buttons. You can access them via the elements
property:
let username = loginFormById.elements["username"];
let password = loginFormById.elements["password"];
console.log(username.value); // Current value
username.value = "JohnDoe"; // Set new value
Looping through all elements in a form:
for (let i = 0; i < loginFormById.elements.length; i++) {
console.log(loginFormById.elements[i].name);
}
let email = document.forms["loginForm"].elements["email"];
email.value = "example@mail.com"; // Set value dynamically
let submitBtn = document.forms["loginForm"].elements["submit"];
submitBtn.disabled = true; // Disable button
submitBtn.disabled = false; // Enable button
let form = document.getElementById("loginForm");
let newInput = document.createElement("input");
newInput.type = "text";
newInput.name = "phone";
newInput.placeholder = "Enter phone number";
form.appendChild(newInput);
let phoneField = form.elements["phone"];
phoneField.parentNode.removeChild(phoneField);
Validation ensures that user input meets required criteria before submission.
loginFormById.addEventListener("submit", function(event) {
let username = loginFormById.elements["username"].value;
let password = loginFormById.elements["password"].value;
if (username === "" || password === "") {
alert("Please fill in all fields.");
event.preventDefault(); // Stop form submission
}
});
let emailField = loginFormById.elements["email"];
emailField.addEventListener("blur", function() {
let emailPattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/;
if (!emailPattern.test(this.value)) {
alert("Invalid email address");
}
});
let hobbies = document.forms["loginForm"].elements["hobbies"];
for (let i = 0; i < hobbies.length; i++) {
if (hobbies[i].checked) {
console.log(hobbies[i].value + " selected");
}
}
let genderRadios = document.forms["loginForm"].elements["gender"];
for (let radio of genderRadios) {
if (radio.checked) {
console.log("Selected gender: " + radio.value);
}
}
let country = document.forms["loginForm"].elements["country"];
console.log("Selected country: " + country.value);
let message = document.forms["loginForm"].elements["message"];
message.value = "Enter your feedback here";
DOM Forms support several events:
submit – Triggered when the form is submitted.
reset – Triggered when the form is reset.
input – Triggered when an input changes.
change – Triggered when a field loses focus after a change.
focus – Triggered when an element gains focus.
blur – Triggered when an element loses focus.
Example:
loginFormById.elements["username"].addEventListener("input", function() {
console.log("Username changed to: " + this.value);
});
<form id="signupForm">
<input type="text" name="username" placeholder="Username">
<input type="email" name="email" placeholder="Email">
<input type="submit" value="Register">
</form>
<div id="output"></div>
let form = document.getElementById("signupForm");
form.addEventListener("submit", function(event) {
event.preventDefault(); // Prevent default submission
let username = form.elements["username"].value;
let email = form.elements["email"].value;
document.getElementById("output").innerHTML =
`<p>Username: ${username}</p><p>Email: ${email}</p>`;
});
When the user submits the form, the values are displayed dynamically without refreshing the page.
Always validate inputs to prevent errors and security issues.
Use elements
collection for easy access to form fields.
Use event listeners for input, submit, and change events instead of inline attributes.
Sanitize user input if adding it to the DOM to avoid XSS attacks.
Use dynamic field creation carefully to maintain form structure and accessibility.
DOM Forms allow you to interact with HTML forms dynamically using JavaScript. With DOM Forms, you can:
Access forms and all form elements using document.forms
or IDs.
Read and set input values, including text, checkbox, radio, and select.
Validate inputs and provide instant feedback to users.
Dynamically add or remove fields programmatically.
Handle form events for submit, reset, input, and change efficiently.
Mastering DOM Forms is essential for creating interactive, user-friendly, and responsive web applications, enabling real-time processing and validation of user input.
Select a form with the ID loginForm
and log all its input element names and values in the console.
Access the username and password fields in a login form and set default values using JavaScript.
Disable the submit button of a form until a text input field is filled by the user.
Dynamically add a new text input field with the name phone
and placeholder "Enter phone number"
to a form.
Remove an input field named phone
from the form dynamically using JavaScript.
Validate a form on submission to ensure all required fields are not empty, and prevent submission if validation fails.
Validate an email input using a regular expression and alert the user if it is invalid.
Access all selected checkboxes in a form named hobbies
and log their values in the console.
Access a group of radio buttons named gender
and display the selected value on form submission.
On form submission, prevent the default action and display all input values dynamically inside a <div>
on the page.
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts