HTML onsubmit Attribute

Beginner
⏱️ 6 min read
📚 Updated: Jun 2026
🎯 3 Examples
Events & Handlers

Introduction

The onsubmit attribute is an inline event handler for the submit event on a <form> element. It runs when the user tries to send the form — by clicking a Submit button, pressing Enter in a text field, or when script calls form.requestSubmit(). Use it to validate data, show errors, or handle submission with JavaScript instead of a full page reload. Return false (inline) or call event.preventDefault() (listener) to cancel submission. Prefer addEventListener("submit", …) in production.

What You’ll Learn

01

Event handler

Inline JS.

02

submit

Form sent.

03

<form>

Target element.

04

return false

Block submit.

05

Validation

Before send.

06

addEventListener

Preferred way.

Purpose of onsubmit Attribute

The primary purpose of onsubmit is to run custom logic before the browser sends form data to the server (or navigates to the action URL). Validate fields, show friendly error messages, transform values, or intercept submission for a single-page app with fetch.

If the handler returns false (inline attribute) or calls event.preventDefault(), the form does not submit and the page does not navigate. If it returns true or does nothing blocking, the browser continues with normal submission.

💡
Native validation runs first

Unless the form has novalidate, the browser checks required, type="email", and other constraints before your onsubmit handler runs. Use custom validation for rules HTML cannot express.

📝 Syntax

Set onsubmit on <form>, or assign form.onsubmit in JavaScript:

onsubmit.html
<form action="/login" method="post" onsubmit="return validateForm()">
  <input type="text" name="username" required>
  <input type="submit" value="Submit">
</form>

<script>
  form.onsubmit = validateForm;
  form.addEventListener("submit", function (event) {
    if (!isValid()) event.preventDefault();
  });
</script>

Syntax Rules

  • Valid on <form> elements only.
  • Value is JavaScript executed when the submit event fires.
  • Inline: return false cancels submission; return true allows it.
  • Listener: use event.preventDefault() to cancel.
  • Triggered by Submit button, button type="submit", Enter in a text field, or requestSubmit().
  • Also assignable as form.onsubmit in script.
  • Modern alternative: addEventListener("submit", handler).

💎 Values

The onsubmit attribute accepts a string of JavaScript code:

  • onsubmit="return validateForm()" — Call a function; return value controls submission.
  • onsubmit="return false" — Always block submission (demo pages).
  • onsubmit="event.preventDefault(); handleSubmit()" — Cancel then run custom logic.
  • JavaScript: form.onsubmit = () => { …; return false; } — property assignment.
onsubmit-handler.js
function validateForm() {
  var username = document.getElementById("username").value.trim();
  var password = document.getElementById("password").value.trim();

  if (username === "" || password === "") {
    status.textContent = "Please fill in all fields";
    status.setAttribute("role", "alert");
    return false; // block submission
  }

  status.textContent = "Validated — sending…";
  return true; // allow submission
}

form.addEventListener("submit", function (event) {
  if (!isValid()) event.preventDefault();
});

⚡ Quick Reference

Actionsubmit fires?Notes
Click input type="submit"YesClassic submit button
Click button type="submit"YesInside the form
Press Enter in text fieldYesImplicit submit
form.requestSubmit()YesRuns validation + handlers
form.submit()NoSkips handlers — avoid for UX
Click type="reset"NoFires reset instead

Applicable Elements

ElementSupported?Notes
<form>YesPrimary and correct target
form.addEventListener("submit")YesRecommended registration
<input>, <button>NoPut handler on parent form
<button type="submit" form="id">IndirectButton submits linked form — handler on that form
<div> or other containersNoNot a form event target

onsubmit vs onreset vs native validation vs form.submit()

API / handlerWhen it firesTypical use
onsubmitUser sends the formValidate, intercept, fetch API
onresetForm cleared to defaultsFeedback, clear custom UI
Native required / typeBefore submit handlerBuilt-in browser validation
form.submit()Immediate, no eventProgrammatic send — skips handlers

Examples Gallery

Login validation with return false, dynamic assignment, and addEventListener with preventDefault.

👀 Live Preview

Submit with empty fields to see validation — valid input shows success:

Waiting for submit…

Example — onsubmit with validation

Return false to block invalid submissions:

form-onsubmit.html
<form onsubmit="return validateForm()">
  <label for="username">Username:</label>
  <input type="text" id="username" name="username">
  <label for="password">Password:</label>
  <input type="password" id="password" name="password">
  <input type="submit" value="Submit">
</form>

<script>
  function validateForm() {
    if (username.value === "" || password.value === "") {
      status.textContent = "Please fill in all fields";
      return false;
    }
    return true;
  }
</script>
Try It Yourself

How It Works

When the user clicks Submit, the browser fires submit on the form. Your function runs first; returning false stops the browser from navigating to the action URL.

Dynamic Values with JavaScript

Assign the handler on the form at runtime:

dynamic-onsubmit.html
<script>
  document.getElementById("dynamicForm").onsubmit = function () {
    log.textContent = "Form submitted dynamically";
    return false;
  };
</script>
Try It Yourself

How It Works

Assigning form.onsubmit is equivalent to the inline attribute. Attach after the form exists in the DOM.

Example — Submit without page reload

Use addEventListener and event.preventDefault() for modern form handling:

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

  var email = emailInput.value.trim();
  status.textContent = "Thanks! We saved: " + email;
  // Later: fetch("/subscribe", { method: "POST", body: … })
});
Try It Yourself

How It Works

preventDefault() stops navigation. You then read form values and send them with fetch, show errors inline, or update the UI — all without a full page reload.

♿ Accessibility

  • Announce errors — Use role="alert" or aria-live="polite" on validation messages.
  • Link errors to fields — Use aria-describedby and aria-invalid="true" on invalid inputs.
  • Do not rely on color alone — Pair red borders with clear text like “Password is required.”
  • Keyboard submit — Enter in a text field submits the form — ensure your handler works for keyboard users too.
  • Avoid alert() — Blocking dialogs are disruptive; use inline status text instead.

🧠 How onsubmit Works

1

User submits

Button or Enter.

Trigger
2

Native validation

Unless novalidate.

Browser
3

submit fires

onsubmit runs.

Event
=

Send or block

Navigate or preventDefault.

Browser Support

The submit event and onsubmit handler are supported in all browsers, including every modern browser and legacy Internet Explorer.

HTML Forms · Universal support

Universal onsubmit support

Every browser that supports HTML forms fires submit when a form is sent.

100% Browser support
Google Chrome Fully supported
Full support
Mozilla Firefox Fully supported
Full support
Apple Safari Fully supported
Full support
Microsoft Edge Fully supported
Full support
Internet Explorer All versions
Full support
Opera Fully supported
Full support
onsubmit attribute 100% supported

Bottom line: One of the most reliable form events — safe to use everywhere.

💡 Best Practices

✅ Do

  • Put onsubmit on the <form> element
  • Use addEventListener("submit", …) with preventDefault() in production
  • Show inline validation errors with aria-live
  • Combine native required with custom rules where needed
  • Use requestSubmit() instead of submit() when triggering from script

❌ Don’t

  • Use alert() for validation feedback
  • Call form.submit() when you need handlers to run
  • Put onsubmit on individual inputs
  • Forget server-side validation — client checks are not enough alone
  • Return false inside addEventListener — use preventDefault()

Conclusion

The onsubmit attribute runs JavaScript when a form is submitted — useful for validation, user feedback, and handling data without a full page reload.

Return false or call preventDefault() to block submission, prefer addEventListener in production, and always validate on the server too.

Key Takeaways

Knowledge Unlocked

Five truths every developer should know about onsubmit

Bookmark these before wiring form handlers.

5
Core concepts
02

return false

Block inline.

Cancel
🔄 03

preventDefault

In listener.

Modern
04

+ required

Native first.

Pair
📤 05

vs onreset

Send vs clear.

Compare

❓ Frequently Asked Questions

It runs JavaScript when the submit event fires — when the user sends a form via a Submit button or Enter key.
In an inline handler, return false. In addEventListener, call event.preventDefault(). Both prevent navigation to the action URL.
onsubmit runs when the user sends form data. onreset runs when the form is cleared to its default values.
No. form.submit() bypasses the submit event and handlers. Use form.requestSubmit() when you need validation and onsubmit to run.
form.addEventListener("submit", handler) is preferred — use event.preventDefault() and attach multiple listeners if needed.
Yes. The submit event is supported in every browser that supports HTML forms.

Master form submission handlers

Practice the onsubmit attribute with validation and preventDefault demos in the Try It editor.

Try login validation →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful