Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / HTML

onsubmit — handling a form submission attempt

The onsubmit attribute specifies JavaScript that handles the submit event. It lets you react to a form submission attempt and cancel the default submission; it does not confirm that data reached the server.

Version: WHATWG HTML Living Standard; index snapshot date recorded separately

Syntax

onsubmit="JavaScript statements"
form.onsubmit = function (event) { /* handler */ };

onsubmit is an event handler attribute for submit. It is normally placed on the form element, not the submit button. Although available on all HTML elements, the form is this event's target; the event bubbles to ancestors. The attribute value is JavaScript code, not the form's destination address.

The event occurs before default submission, for example after activating a submit button or calling form.requestSubmit(). If the browser performs constraint validation and the form fails it, submit does not occur. The form.submit() method bypasses both that validation and the submit event.

The attribute's code receives the event parameter. Calling event.preventDefault() or executing return false cancels default submission. This does not stop event propagation. Merely calling a function that returns false, without forwarding its result with return, does not cancel submission.

JavaScript can also assign a function to form.onsubmit; another assignment replaces the previous function in that property. The example uses the attribute, cancels submission, and changes the status text. It requires JavaScript to be enabled and a security policy that permits inline event handlers.

Examples

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>onsubmit demo</title>
<form onsubmit="event.preventDefault(); document.getElementById('result').textContent = 'Submission canceled';">
  <button type="submit">Submit</button>
</form>
<p id="result" role="status">Ready</p>
</html>

Result

Submission canceled

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources