jQuery - prevent default, then continue default

后端 未结 10 1434
[愿得一人]
[愿得一人] 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:39

    I would just do:

     $('#submiteButtonID').click(function(e){
         e.preventDefault();
         //do your stuff.
         $('#formId').submit();
     });
    

    Call preventDefault at first and use submit() function later, if you just need to submit the form

    0 讨论(0)
  • 2020-12-02 16:42
    $('#myform').on('submit',function(event){
      // block form submit event
      event.preventDefault();
    
      // Do some stuff here
      ...
    
      // Continue the form submit
      event.currentTarget.submit();
    });
    
    0 讨论(0)
  • 2020-12-02 16:42

    In a pure Javascript way, you can submit the form after preventing default.

    This is because HTMLFormElement.submit() never calls the onSubmit(). So we're relying on that specification oddity to submit the form as if it doesn't have a custom onsubmit handler here.

    var submitHandler = (event) => {
      event.preventDefault()
      console.log('You should only see this once')
      document.getElementById('formId').submit()
    }
    

    See this fiddle for a synchronous request.


    Waiting for an async request to finish up is just as easy:

    var submitHandler = (event) => {
      event.preventDefault()
      console.log('before')
      setTimeout(function() {
        console.log('done')
        document.getElementById('formId').submit()
      }, 1400);
      console.log('after')
    }
    

    You can check out my fiddle for an example of an asynchronous request.


    And if you are down with promises:

    var submitHandler = (event) => {
      event.preventDefault()
      console.log('Before')
        new Promise((res, rej) => {
          setTimeout(function() {
            console.log('done')
            res()
          }, 1400);
        }).then(() => {
          document.getElementById('bob').submit()
        })
      console.log('After')
    }
    

    And here's that request.

    0 讨论(0)
  • 2020-12-02 16:43

    Use jQuery.one()

    Attach a handler to an event for the elements. The handler is executed at most once per element per event type

    $('form').one('submit', function(e) {
        e.preventDefault();
        // do your things ...
    
        // and when you done:
        $(this).submit();
    });
    

    The use of one prevent also infinite loop because this custom submit event is detatched after the first submit.

    0 讨论(0)
  • 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);
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form action="/" id="my-form">
      <input name="./fname" value="John" />
      <input name="./lname" value="Smith" />
      <input type="submit" value="Lets Do This!" />
      <br>
      <label>
        <input type="checkbox" value="true" id="allIsWell" />
        All Is Well
      </label>
    </form>

    Good Luck...

    0 讨论(0)
  • 2020-12-02 16:52

    "Validation injection without submit looping":

    I just want to check reCaptcha and some other stuff before HTML5 validation, so I did something like that (the validation function returns true or false):

    $(document).ready(function(){
       var application_form = $('form#application-form');
    
       application_form.on('submit',function(e){
    
            if(application_form_extra_validation()===true){
               return true;
            }
    
            e.preventDefault();
    
       });
    });
    
    0 讨论(0)
提交回复
热议问题