Run an animation before I submit a form (and make

2019-07-23 07:52发布

问题:

So I have a little form (#edit_form) with elements from a database. The checked elements are assigned the class .selected, and when the user submits the form, I want them to slide up before the form is actually submitted and the page reloads. I have tried this:

$("#edit_form").submit(function(){
    $('.selected').slideUp(800,function(){
        $("#edit_form").submit();
    });
});

The problem is that the form just submits, and doesn't wait until the animation is complete. I have also tried this:

$("#edit_form").submit(function(e){
    e.preventDefault();
    $('.selected').slideUp(800,function(){
        $("#edit_form").submit();
    });
});

This makes the animation fire, but the form is never submitted. Here is another one I tried (the submit button has an id of #formsubmit):

$("#formsubmit").click(function(e){
    e.preventDefault();
    $('.selected').slideUp(800,function(){
        $("#edit_form").submit();
    });
});

I have tried that with and without the preventDefault(), and they both do the same as if I am trying to intercept the form submit action. Anybody have any other ideas?

回答1:

Your second example is close, however the javascript enters an infinite loop. Do you see it?

When the submit event is handled you call preventDefault. Thus, when you submit it programmatically ($("#edit_form").submit();) the submit event is just called again, and you prevent it again, and so on.

To solve this, unbind the submit event before programmatically submitting the form:

$("#edit_form").unbind("submit").submit();

Full code:

$("#edit_form").submit(function(e)
{
    e.preventDefault();
    $('.selected').slideUp(800,function()
    {
        $("#edit_form").unbind("submit").submit();
    });
});

Edit: I was wrong. Fixed code.



标签: jquery forms