Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Surprised, I am encountering this weird issue while submitting form from JS.

Issue:

Consider a simple form submitted using two ways from a submit button and an anchor link

<form method="POST" action="page.html" name="foobar" id="test">
  <input type="text" />
  <input type="submit" />
</form>

<a href="#" onclick="document.getElementById('test').submit();">click me</a>

Function catching the submit event

document.getElementById('test').onsubmit = function() {
   // Same result with 
   //     * document.foobar.onsubmit
   //     * document.forms['foobar'].onsubmit

   alert('foobar');
   return false;
}

Now, when the form is submitted from clicking the submit button I get the alert, but not when clicking the link. Why is this doing so?

Fiddle Showing the Issue

like image 791
Starx Avatar asked Oct 10 '12 12:10

Starx


2 Answers

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.

like image 189
RobG Avatar answered Sep 22 '22 13:09

RobG


Thats how form.submit behaves;

The form's onsubmit event handler (for example, onsubmit="return false;") will not be triggered when invoking this method from Gecko-based applications. In general, it is not guaranteed to be invoked by HTML user agents

Make onsubmit call a function and simply call that onclick as well.

like image 44
Alex K. Avatar answered Sep 22 '22 13:09

Alex K.