Preventing one form submission, and submitting ano

2019-07-24 00:11发布

问题:

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.