jQuery - prevent default, then continue default

JavascriptJquery

Javascript Problem Overview


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 additional processing (it's basically calling Google Maps API and adding a few hidden fields to the form) -- and then I need the form to submit.

Is there a way to "prevent default", then some point later "continue default?"

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

When you bind the .submit() event to the form, and you do the things you want to do before returning (true), these things happen prior to the actual submission.

For example:

$('form').submit(function(){
	alert('I do something before the actual submission');
  	return true;
});

Simple example

Another example on jquery.com: http://api.jquery.com/submit/#entry-examples

Solution 3 - Javascript

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

Solution 4 - Javascript

Using this way You will do a endless Loop on Your JS. to do a better way you can use the following

var on_submit_function = function(evt){
    evt.preventDefault(); //The form wouln't be submitted Yet.
    (...yourcode...)

    $(this).off('submit', on_submit_function); //It will remove this handle and will submit the form again if it's all ok.
    $(this).submit();
}

$('form').on('submit', on_submit_function); //Registering on submit.

I hope it helps! Thanks!

Solution 5 - Javascript

      $('#myform').on('submit',function(event){
        // block form submit event
        event.preventDefault();

        // Do some stuff here
        ...

        // Continue the form submit
        event.currentTarget.submit();
  });

Solution 6 - Javascript

This is, IMHO, the most generic and robust solution (if your actions are user-triggered, eg 'user clicks on a button'):

  • the first time a handler is called check WHO triggered it:
    • if a user tiggered it - do your stuff, and then trigger it again (if you want) - programmatically
    • otherwise - do nothing (= "continue default")

As an example, note this elegant solution to adding "Are you sure?" popup to any button just by decorating a button with an attribute. We will conditionally continue default behavior if the user doesn't opt out.

Let's add to every button that we want an "are you sure" popup a warning text:

<button class="btn btn-success-outline float-right" type="submit"  ays_text="You will lose any unsaved changes... Do you want to continue?"                >Do something dangerous</button>

2. Attach handlers to ALL such buttons:

$('button[ays_text]').click(function (e, from) {
    if (from == null) {  // user clicked it!
        var btn = $(this);
        e.preventDefault();
        if (confirm() == true) {
            btn.trigger('click', ['your-app-name-here-or-anything-that-is-not-null']);
        }
    }
    // otherwise - do nothing, ie continue default
});

That's it.

Solution 7 - Javascript

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...

Solution 8 - Javascript

"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();
                        
   });
});

Solution 9 - Javascript

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.

Solution 10 - Javascript

You can use e.preventDefault() which will stop the current operation.

than you can do $("#form").submit();

 $('#form').submit(function (e)
{
	return !!e.submit;
});
if(blabla...)
{...
}
else
{
	$('#form').submit(
	{
		submit: true
	});
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionStackOverflowNewbieView Question on Stackoverflow
Solution 1 - JavascriptAurelView Answer on Stackoverflow
Solution 2 - JavascriptRon van der HeijdenView Answer on Stackoverflow
Solution 3 - JavascriptbipenView Answer on Stackoverflow
Solution 4 - JavascriptJoepreludianView Answer on Stackoverflow
Solution 5 - JavascriptUdy WarnasuriyaView Answer on Stackoverflow
Solution 6 - JavascriptigorludiView Answer on Stackoverflow
Solution 7 - JavascriptAakashView Answer on Stackoverflow
Solution 8 - JavascriptDennis HeidenView Answer on Stackoverflow
Solution 9 - JavascriptalairockView Answer on Stackoverflow
Solution 10 - JavascriptRoyi NamirView Answer on Stackoverflow