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
997 views
in Technique[技术] by (71.8m points)

javascript - Form onsubmit versus submit button onclick

UPDATE From @BrendanEich ?

@mplungjan onclick of submit just falls out of that being a button; form onsubmit is clearly better.


Which would be the reasons to ever use the onclick of a submit button to determine whether or not the form should be submitted?

I believe strongly that

  1. to execute something before submit and cancel the submit in case of error, the form's onsubmit event is the obvious place to put it
  2. If you use the onclick of a submit button and later decide to use type="image" the event handler will fail in many browsers
  3. if you change the submit to a button, you will have to add a submit to the onclick event handler too.

I am looking for strong reasons to prefer using a submit button's onclick event over the form's onsubmit.

UPDATE: Please not that I am personally well aware of many of the issues around form submission and validation.
For example that submitting by javascript will not trigger the onsubmit http://jsfiddle.net/mplungjan/3A4Ha/

<form onsubmit="alert('onSubmit called')">
    <input type="text" value="This will submit on enter but in IE the onclick is not triggered" style="width:100%"/><br/>
    <input type="submit" onclick="alert('Clicked')" />
</form><br />
<a href="#" onclick="alert('Submitting by script'); return false">Submit by script will not trigger onsubmit</a>

Also that IE will not trigger the onclick if you hit enter in the form in my fiddle


History:

Got into a discussion here

html button not clickable without being disabled

I have an intense dislike of using the onclick of a submit button for ANYTHING due to many1 years of seeing this not work in a number of browsers, mostly older version of IE. I have listed a few of the obvious reasons, but I am sure they will not convince the hardened user.

Can SO's community help me nail this one to the wall, like they nailed w3schools? Also feel free to give comments as to how I can phrase this question in an acceptable manner.


1: since the days of NS2.x and IE3.02

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Form onsubmit is a more correct approach, for the simple reason that a form can also be submitted with the <ENTER> key, and not just by clicking the submit button.


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

...