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

Should jQuery's $(form).submit(); not trigger onSubmit within the form tag?

I have the following:

<script type="text/javascript">
function CancelFormButton(button) {
    $(button.form).submit();
}
</script>

<form onsubmit="alert('here');">
<input type="button" value="Cancel" onClick="CancelFormButton(this);" />
</form>

When I click the "Cancel" button, the onsubmit from the form tag is not triggered.

This line instead submits the form successfully: $(button.form).submit(); but skips the alert('here'); within the onsubmit in the form tag.

Is this correct or am I doing something wrong?

By the way, in this case, I want this functionality, but I'm just wondering if I'm going to run into a problem in a browser where the onsubmit is triggered.

question from:https://stackoverflow.com/questions/645555/should-jquerys-form-submit-not-trigger-onsubmit-within-the-form-tag

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

1 Reply

0 votes
by (71.8m points)

Sorry, misunderstood your question.

According to Javascript - capturing onsubmit when calling form.submit():

I was recently asked: "Why doesn't the form.onsubmit event get fired when I submit my form using javascript?"

The answer: Current browsers do not adhere to this part of the html specification. The event only fires when it is activated by a user - and does not fire when activated by code.

(emphasis added).

Note: "activated by a user" also includes hitting submit buttons (probably including default submit behaviour from the enter key but I haven't tried this). Nor, I believe, does it get triggered if you (with code) click a submit button.


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

...