Form Handling

  • This lesson covers JavaScript techniques for handling and validating forms.
  • Introduction to Form Handling in JavaScript

    Forms are a critical part of any website or web application.
    They are used to collect data from users, such as:

    • Login details

    • Registration information

    • Feedback

    • Contact details

    • Search queries

    Form handling using DOM means:

    Accessing, reading, validating, and controlling form data using JavaScript.

    What is DOM in Form Handling ?

    The DOM (Document Object Model) represents the HTML document as objects.

    Using DOM, JavaScript can:

    • Access form elements

    • Read user input

    • Modify form values

    • Validate data

    • Prevent incorrect submission

    Why Form Handling is Important ?

    Without JavaScript:

    • Forms submit blindly

    • Errors go to server

    • Poor user experience

    With JavaScript:

    • Instant validation

    • Error messages without reload

    • Better data quality

    • Faster interaction

Introduction to Form Handling Using DOM

Explains how JavaScript interacts with forms to read, validate, and control user input

<form id="myForm">
  <label>Name:</label>
  <input type="text" id="username">

  <br><br>

  <label>Password:</label>
  <input type="password" id="password">

  <br><br>

  <button type="submit">Submit</button>
</form>
  • Accessing Form Elements Using DOM

Accessing and Reading Form Input Values

Uses DOM methods to get form elements and read user-entered data

// Access inputs
let nameInput = document.getElementById("username");
let passwordInput = document.getElementById("password");

// Read values
let username = nameInput.value;
let password = passwordInput.value;

console.log(username, password);
  • The .value property is used to get input data.

    Handling Form Submission

    By default, when a form is submitted:

    • Page reloads

    • Data is sent to server

    JavaScript allows us to control this behavior.

Handling Form Submission Using onsubmit Event

Executes a function when a form is submitted

<form onsubmit="handleSubmit()">
  <button type="submit">Submit</button>
</form>

<script>
function handleSubmit() {
  console.log("Form submitted");
}
</script>
  • However, this still reloads the page.

Prevent Form Reload Using event.preventDefault()

Stops default form submission behavior to handle data

<form id="myForm">
  <button type="submit">Submit</button>
</form>

<script>
let form = document.getElementById("myForm");

form.addEventListener("submit", function (event) {
  event.preventDefault();
  console.log("Form submitted without reload");
});
</script>
  • Why preventDefault() is Important ?

    • Stops page refresh

    • Allows validation

    • Enables AJAX/API calls

    • Improves user experience

    Basic Form Validation Using DOM

Basic Form Validation Using DOM

Validates user input and prevents submission if fields are empty

let form = document.getElementById("myForm");

// Single field validation
form.addEventListener("submit", function (event) {
  event.preventDefault();

  let username = document.getElementById("username").value;

  if (username === "") {
    alert("Name is required");
  } else {
    alert("Form submitted successfully");
  }
});

// Multiple field validation
form.addEventListener("submit", function (event) {
  event.preventDefault();

  let name = document.getElementById("username").value;
  let pass = document.getElementById("password").value;

  if (name === "" || pass === "") {
    alert("All fields are required");
  } else {
    alert("Form submitted");
  }
});
  • Displaying Error Messages in HTML

Display Validation Errors in DOM

Shows error messages on the page instead of using alerts

<!-- HTML -->
<p id="error" style="color:red;"></p>

<script>
// JavaScript
let errorMsg = document.getElementById("error");

if (name === "") {
  errorMsg.textContent = "Name cannot be empty";
}
</script>
  • Handling Different Form Inputs

Handling Different Types of Form Inputs

Demonstrates how to read values from checkbox, radio buttons, and dropdown

<!-- Checkbox -->
<input type="checkbox" id="agree">

<!-- Radio Buttons -->
<input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female

<!-- Select Dropdown -->
<select id="city">
  <option value="">Select City</option>
  <option value="Delhi">Delhi</option>
  <option value="Mumbai">Mumbai</option>
</select>

<script>
// Checkbox value
let agree = document.getElementById("agree").checked;

// Radio button value
let gender = document.querySelector('input[name="gender"]:checked').value;

// Dropdown value
let city = document.getElementById("city").value;

console.log(agree, gender, city);
</script>
  • Resetting Form Using DOM

    form.reset();

    This clears all input fields.

Reset Form and Validate Login Credentials

Clears form inputs and checks user login details

// Reset form
form.reset(); // clears all fields

// Login validation
form.addEventListener("submit", function (event) {
  event.preventDefault();

  let user = document.getElementById("username").value;
  let pass = document.getElementById("password").value;

  if (user === "admin" && pass === "1234") {
    alert("Login successful");
  } else {
    alert("Invalid credentials");
  }
});
  • Common Beginner Mistakes

    • Forgetting .value

    • Not preventing default submission

    • Using inline JavaScript excessively

    • Not validating inputs

    • Ignoring empty fields

    Best Practices for Form Handling

    • Always validate user input

    • Use addEventListener instead of inline events

    • Show clear error messages

    • Prevent page reload when needed

    • Keep logic clean and readable