Form submitted multiple times when using the “submit” callback and $.ajax to post it

后端 未结 8 1526
闹比i
闹比i 2020-12-14 17:50

I\'ve been observing some strange behavior with the following code:

$.fn.submit_to_remote = function() {
  // I use .each instead of the .submit directly so          


        
8条回答
  •  孤城傲影
    2020-12-14 18:22

    Unbind didn't work for me. This did:

    $(document).off('submit');
    $(document).on('submit',"#element_id",function(e){
        e.preventDefault();
        //do something
    }); 
    

    I hope it helps...

    In fact unbind() can bring you some troubles if you have some validation and return before submit. Example:

    $(document).on('submit',"#element_id",function(e){
        e.preventDefault();
        $(document).unbind('submit');
        var name = $(this).children('input[name="name"]').val();
        if( name == 'wrong name')
            return;
    
        //do something
    });
    

    In this case if you input is 'wrong name' the form will not be submitted and after that, when you put the "right name", the $(document).on('submit'.. will not be triggered, neither the e.preventDefault(); and your form will be submitted in the regular way .

提交回复
热议问题