jQuery: Stop submitting form, perform script, cont

2019-03-12 18:37发布

I have a form, and when I submit him I execute multiple script. Here is my code:

$("#RequestCreateForm").submit(function (e) {
    if ($("#RequestCreateForm").validate().checkForm() == false) { return; }

    e.preventDefault();

    //many scripts

    //How to continue submitting?
}

Is it possible to continue submitting the form (which is stopped with e.preventDefault();) after //many scripts?

Thank you

8条回答
Emotional °昔
2楼-- · 2019-03-12 19:23

To avoid submit loops, an additional variable should be used.

var codeExecuted = false;
$('#RequestCreateForm').submit(function(e) {
    ...
    if(!codeExecuted){
        e.preventDefault();
        ...
        functionExecuted = true;
        $(this).trigger('submit');
    }
});
查看更多
你好瞎i
3楼-- · 2019-03-12 19:23

Here is my approach to avoid the infinite loop.

  • In the form, I use a "button" with an id (e.g. <input type="button" id="submit" value="submit"/>) to mimic the submit button;
  • In the script I have something like this:
$('#submit').click(function() {
  if(//validation rules is ok)
  {
      $("#RequestCreateForm").submit(); //assuming the form id is #RequestCreateForm
  }
  else
  {
      return false;
  }
});
查看更多
等我变得足够好
4楼-- · 2019-03-12 19:23

return; is the same thing as e.preventDefault();

try

$("#RequestCreateForm").trigger('submit');
查看更多
老娘就宠你
5楼-- · 2019-03-12 19:32

$("#RequestCreateForm").submit(function (e) {
    if ($("#RequestCreateForm").validate().checkForm() === false) { 
       e.preventDefault(); 
       //form was NOT ok - optionally add some error script in here

       return false; //for old browsers 
    } else{
       //form was OK - you can add some pre-send script in here
    }

    //$(this).submit(); 
    //you don't have to submit manually if you didn't prevent the default event before
}
查看更多
迷人小祖宗
6楼-- · 2019-03-12 19:37
$("#RequestCreateForm").submit(function (e) {
    if ($("#RequestCreateForm").validate().checkForm() == false) { return; }

    e.preventDefault();

    //many scripts

    // Bypass the jquery form object submit and use the more basic vanilla
    // javascript form object submit

    $("#RequestCreateForm")[0].submit();

}
查看更多
Lonely孤独者°
7楼-- · 2019-03-12 19:39

All solutions here are too complicated or lead to javascript error, simpliest and clearest solution I guess:

jQuery("#formid").submit(function(e) {
        if( ! (/*check form*/)  ){  //notice the "!"
          e.preventDefault();
          //a bit of your code
        } //else do nothing, form will submit
}); 
查看更多
登录 后发表回答