learn2kode.in

JavaScript Forms & Input Handling

Forms are one of the most important parts of any website. They allow users to submit data such as login details, contact information, feedback, and more. JavaScript forms & input handling help you capture, validate, and process this data before sending it to the server.
In this tutorial, you’ll learn how to work with form elements, read input values, handle events, and perform basic validation using JavaScript.

Accessing Form Elements in JavaScript

You can access form elements using different methods:
<form id="contactForm">
  <input type="text" id="username" placeholder="Enter name">
  <input type="email" id="email" placeholder="Enter email">
  <button type="submit">Submit</button>
</form>
const form = document.getElementById("contactForm");
const username = document.getElementById("username");
const email = document.getElementById("email");
Getting Input Values

To get the value entered by a user, use the .value property:

console.log(username.value);
console.log(email.value);
This is commonly used when the form is submitted.
Handling Form Submit Event
JavaScript allows you to control what happens when a form is submitted.
form.addEventListener("submit", function (event) {
  event.preventDefault(); // prevents page reload

  console.log("Name:", username.value);
  console.log("Email:", email.value);
});
Using event.preventDefault() stops the browser’s default form submission behavior.
Basic Form Validation

Validation ensures users enter correct and complete data.

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

  if (username.value === "") {
    alert("Username is required");
    return;
  }

  if (email.value === "") {
    alert("Email is required");
    return;
  }

  alert("Form submitted successfully!");
});
Handling Different Input Types
JavaScript supports all input types:
<input type="checkbox" id="agree">
<input type="radio" name="gender" value="male">
<select id="country">
  <option value="india">India</option>
  <option value="usa">USA</option>
</select>
document.getElementById("agree").checked;
document.getElementById("country").value;
Real-Time Input Handling (keyup / change)

You can listen for real-time input changes:

username.addEventListener("keyup", function () {
  console.log("Typing:", username.value);
});
Common Form Events
Event Description
submit Triggered when form is submitted
change Fired when input value changes
focus Input gains focus
blur Input loses focus
keyup User releases a key
HTML Table Code
Event Description
submit Triggered when form is submitted
change Fired when input value changes
focus Input gains focus
blur Input loses focus
keyup User releases a key
Best Practices for Form Handling