Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

javascript - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...