Form submitted using submit() from a link cannot be caught by onsubmit handler

To provide a reasonably definitive answer, the HTML Form Submission Algorithm item 5 states that a form only dispatches a submit event if it was not submitted by calling the submit method (which means it only dispatches a submit event if submitted by a button or other implicit method, e.g. pressing enter while focus is on an input type text element).

If no submit event is dispatched, then the submit handler won’t be called.

That is different to the DOM 2 HTML specification, which said that the submit method should do what the submit button does.

So if you want to use script to submit a form, you should manually call the submit listener. If the listener was added using addEventListener, then you’ll need to remember that and to call it since you can’t discover it by inspecting the form (as suggested below).

If the listener is set inline, or added to the DOM onsubmit property, you can do something like:

<form onsubmit="return validate(this);" ...>
  ...
</form>
<button onclick="doSubmit()">submit form</button>

<script>
function doSubmit() {
  var form = document.forms[0];

  if (form.onsubmit) {
    var result = form.onsubmit.call(form);
  }

  if (result !== false) {
    form.submit();
  }
}
</script>

Life is tougher if you need to pass parameters or do other things.

Leave a Comment