jQuery - prevent default, then continue default

后端 未结 10 1563
[愿得一人]
[愿得一人] 2020-12-02 16:27

I have a form that, when submitted, I need to do some additional processing before it should submit the form. I can prevent default form submission behavior, then do my addi

10条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-02 16:44

    With jQuery and a small variation of @Joepreludian's answer above:

    Important points to keep in mind:

    • .one(...) instead on .on(...) or .submit(...)
    • named function instead of anonymous function since we will be referring it within the callback.

    $('form#my-form').one('submit', function myFormSubmitCallback(evt) {
        evt.stopPropagation();
        evt.preventDefault();
        var $this = $(this);
        if (allIsWell) {
            $this.submit(); // submit the form and it will not re-enter the callback because we have worked with .one(...)
        } else {
            $this.one('submit', myFormSubmitCallback); // lets get into the callback 'one' more time...
        }
    });
    

    You can change the value of allIsWell variable in the below snippet to true or false to test the functionality:

    $('form#my-form').one('submit', function myFormSubmitCallback(evt){
      evt.stopPropagation();
      evt.preventDefault();
      var $this = $(this);
      var allIsWell = $('#allIsWell').get(0).checked;
      if(allIsWell) {
        $this.submit();
      } else {
        $this.one('submit', myFormSubmitCallback);
      }
    });
    
    

    Good Luck...

提交回复
热议问题