Preventing one form submission, and submitting another - is this approach reliable?

本秂侑毒 提交于 2019-12-11 00:57:39

问题


Is it safe to - within a submit event handler for one form - submit another form and return false to prevent the submission of the first form?

$("#form1").submit(function() {
    $("#form2").submit();
    return false;
});

I am using this approach, and it works (in IE6 at least). However, I am concerned that this might not work in other browsers. Could the call to submit cancel out the return false somehow?

The alternative approach I was considering is

$("#form1").submit(function() {
    setTimeout('$("#form2").submit();', 10);
    return false;
});

....but this might well be adding complexity where none is actually needed.

The reason for needing to do this is that the user is submitting form1, but in a certain scenario (which I can detect using JavaScript) this is causing a bug, that can be rectified instead by setting some data in one of form2's fields and then submitting this form instead.


回答1:


Your code should work across all browsers, but if you want to be absolutely sure you could do

$("#form1").submit(function(evt) {
    evt.preventDefault(); // cancel the default behavior
    $("#form2").submit();
    return false;
});

Using the .preventDefault() method ensures that you cancel the default behavior before doing something that might interfere with it..




回答2:


Your original approach should work everywhere.



来源:https://stackoverflow.com/questions/4193612/preventing-one-form-submission-and-submitting-another-is-this-approach-reliab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!