HTML onsubmit Event Attribute

The HTML onsubmit event attribute is triggered when a form is submitted in an HTML document. This attribute allows you to execute JavaScript code when a user submits a form, enabling form validation, data processing, or other custom actions before the form data is sent to the server.

Syntax

Following is the syntax for the onsubmit event attribute −

<form onsubmit="script">
   form content
</form>

The script parameter contains JavaScript code or a function call that executes when the form is submitted. The function can return false to prevent the form submission or true to allow it.

Basic Form Submission

The onsubmit event fires when the user clicks a submit button or presses Enter in a form field. It provides an opportunity to validate form data before submission.

Example

Following example demonstrates the basic usage of the onsubmit event attribute −

<!DOCTYPE html>
<html>
<head>
   <title>HTML onsubmit Event Attribute</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Contact Form</h2>
   <form onsubmit="submitFn()">
      <label for="name">Name:</label><br>
      <input type="text" id="name" name="name" required><br><br>
      
      <label for="email">Email:</label><br>
      <input type="email" id="email" name="email" required><br><br>
      
      <label for="message">Message:</label><br>
      <textarea id="message" name="message" rows="4" cols="50" placeholder="Enter your message here"></textarea><br><br>
      
      <input type="submit" value="Submit Form">
   </form>
   
   <script>
      function submitFn() {
         alert("Form was submitted successfully!");
      }
   </script>
</body>
</html>

When the user clicks "Submit Form", the onsubmit event triggers and displays an alert message before the form is submitted −

Contact Form
Name: [text input]
Email: [email input]
Message: [textarea]
[Submit Form] button

(Clicking submit shows: "Form was submitted successfully!")

Form Validation with onsubmit

A common use of the onsubmit event is to validate form data before submission. By returning false from the event handler, you can prevent the form from being submitted if validation fails.

Example

Following example shows form validation using the onsubmit event −

<!DOCTYPE html>
<html>
<head>
   <title>Form Validation with onsubmit</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>User Registration</h2>
   <form onsubmit="return validateForm()">
      <label for="username">Username:</label><br>
      <input type="text" id="username" name="username"><br><br>
      
      <label for="password">Password:</label><br>
      <input type="password" id="password" name="password"><br><br>
      
      <input type="submit" value="Register">
   </form>
   
   <div id="error-message" style="color: red; margin-top: 10px;"></div>
   
   <script>
      function validateForm() {
         var username = document.getElementById("username").value;
         var password = document.getElementById("password").value;
         var errorDiv = document.getElementById("error-message");
         
         if (username.length < 3) {
            errorDiv.textContent = "Username must be at least 3 characters long";
            return false; // Prevent form submission
         }
         
         if (password.length < 6) {
            errorDiv.textContent = "Password must be at least 6 characters long";
            return false; // Prevent form submission
         }
         
         errorDiv.textContent = ""; // Clear error message
         alert("Registration successful!");
         return true; // Allow form submission
      }
   </script>
</body>
</html>

The form validates input fields and prevents submission if validation fails. Error messages are displayed, and the form only submits when all validations pass.

User Registration
Username: [text input]
Password: [password input]
[Register] button

(If username < 3 chars: "Username must be at least 3 characters long")
(If password < 6 chars: "Password must be at least 6 characters long")
(If valid: "Registration successful!" and form submits)

Using onsubmit with Event Object

The onsubmit event handler can also receive an event object, which provides additional information about the submission event and methods to control it.

Example

Following example demonstrates using the event object in onsubmit −

<!DOCTYPE html>
<html>
<head>
   <title>onsubmit with Event Object</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Newsletter Subscription</h2>
   <form onsubmit="handleSubmit(event)">
      <label for="email">Email Address:</label><br>
      <input type="email" id="email" name="email" required><br><br>
      
      <label>
         <input type="checkbox" id="agree" name="agree">
         I agree to receive newsletters
      </label><br><br>
      
      <input type="submit" value="Subscribe">
   </form>
   
   <div id="status"></div>
   
   <script>
      function handleSubmit(event) {
         var email = document.getElementById("email").value;
         var agree = document.getElementById("agree").checked;
         var status = document.getElementById("status");
         
         if (!agree) {
            event.preventDefault(); // Prevent form submission
            status.innerHTML = "<p style='color: red;'>Please agree to receive newsletters</p>";
            return;
         }
         
         // Simulate successful subscription
         event.preventDefault(); // Prevent actual submission for demo
         status.innerHTML = "<p style='color: green;'>Thank you! Subscription successful for " + email + "</p>";
      }
   </script>
</body>
</html>

Using event.preventDefault() provides more control over form submission compared to returning false. The example validates the checkbox and shows appropriate feedback.

Newsletter Subscription
Email Address: [email input]
? I agree to receive newsletters
[Subscribe] button

(Without checkbox: "Please agree to receive newsletters" in red)
(With checkbox: "Thank you! Subscription successful for [email]" in green)
onsubmit Event Flow User Clicks Submit onsubmit Triggered JavaScript Executes Return true/undefined Return false Form Submits Submission Cancelled

Common Use Cases

The onsubmit event attribute is commonly used for −

  • Form Validation − Check if required fields are filled and data formats are correct before submission.

  • Data Processing − Modify or format form data before sending it to the server.

  • User Confirmation − Ask for user confirmation before submitting important forms like delete operations.

  • Analytics Tracking − Track form submissions for analytics purposes.

  • AJAX Submissions − Prevent default form submission and handle it via JavaScript/AJAX instead.

Return Values

The onsubmit event handler can control form submission through return values −

Return Value Result
true or undefined Form submission proceeds normally
false Form submission is cancelled
event.preventDefault() Form submission is prevented (recommended modern approach)

Conclusion

The HTML onsubmit event attribute provides a powerful way to execute JavaScript code when a form is submitted. It is essential for form validation, data processing, and controlling the submission process. By returning false or using event.preventDefault(), you can prevent form submission when necessary, making it a crucial tool for creating interactive and validated web forms.

Updated on: 2026-03-16T21:38:54+05:30

484 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements