JavaScript

coding learning websites codepractice

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 Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript DOM Forms


What Are DOM Forms?

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.

Why DOM Forms Are Important

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.

Accessing Forms in the DOM

Using the document.forms Collection

All 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

Accessing Forms by Name or ID

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

Accessing Form Elements

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);
}

Modifying Form Elements Dynamically

Changing Input Values

let email = document.forms["loginForm"].elements["email"];
email.value = "example@mail.com"; // Set value dynamically

Disabling or Enabling Fields

let submitBtn = document.forms["loginForm"].elements["submit"];
submitBtn.disabled = true;  // Disable button
submitBtn.disabled = false; // Enable button

Adding New Input Fields

let form = document.getElementById("loginForm");
let newInput = document.createElement("input");
newInput.type = "text";
newInput.name = "phone";
newInput.placeholder = "Enter phone number";
form.appendChild(newInput);

Removing Fields

let phoneField = form.elements["phone"];
phoneField.parentNode.removeChild(phoneField);

Form Validation Using DOM

Validation ensures that user input meets required criteria before submission.

Simple Validation

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
    }
});

Advanced Validation

let emailField = loginFormById.elements["email"];
emailField.addEventListener("blur", function() {
    let emailPattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/;
    if (!emailPattern.test(this.value)) {
        alert("Invalid email address");
    }
});

Handling Different Input Types

Checkboxes

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");
    }
}

Radio Buttons

let genderRadios = document.forms["loginForm"].elements["gender"];
for (let radio of genderRadios) {
    if (radio.checked) {
        console.log("Selected gender: " + radio.value);
    }
}

Select Dropdown

let country = document.forms["loginForm"].elements["country"];
console.log("Selected country: " + country.value);

Textarea

let message = document.forms["loginForm"].elements["message"];
message.value = "Enter your feedback here";

Form Events

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);
});

Practical Example: Dynamic Form Submission

<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.

Best Practices

  • 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.

Summary of the Tutorial

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.


Practice Questions

  1. Select a form with the ID loginForm and log all its input element names and values in the console.

  2. Access the username and password fields in a login form and set default values using JavaScript.

  3. Disable the submit button of a form until a text input field is filled by the user.

  4. Dynamically add a new text input field with the name phone and placeholder "Enter phone number" to a form.

  5. Remove an input field named phone from the form dynamically using JavaScript.

  6. Validate a form on submission to ensure all required fields are not empty, and prevent submission if validation fails.

  7. Validate an email input using a regular expression and alert the user if it is invalid.

  8. Access all selected checkboxes in a form named hobbies and log their values in the console.

  9. Access a group of radio buttons named gender and display the selected value on form submission.

  10. On form submission, prevent the default action and display all input values dynamically inside a <div> on the page.


JavaScript

online coding class codepractice

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 Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top