Preventing one form submission, and submitting ano

2019-07-24 00:01发布

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.

2条回答
萌系小妹纸
2楼-- · 2019-07-24 00:34

Your original approach should work everywhere.

查看更多
来,给爷笑一个
3楼-- · 2019-07-24 00:51

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

查看更多
登录 后发表回答