88

I have a web page which I have prevented the default action on all submit buttons, however I would like to re-enable default submit action on a button how can I do this?

I am currently preventing the default action using the following:

$("form").bind("submit", function(e){
e.preventDefault();
});

I have successfully done this using the following:

$(document).ready(function(){
$("form:not('#press')").bind("submit", function(e){
e.preventDefault();
});

But can I do this dynamically when the button is clicked?

Richbits
  • 7,344
  • 8
  • 33
  • 38
  • Possible duplicate of [how to enable default after event.preventDefault()?](http://stackoverflow.com/questions/1551389/how-to-enable-default-after-event-preventdefault) – T.Todua Jun 30 '16 at 20:23

7 Answers7

129

You would have to unbind the event and either rebind to a separate event that does not preventDefault or just call the default event yourself later in the method after unbinding. There is no magical event.cancelled=false;

As requested

 $('form').submit( function(ev){

         ev.preventDefault();

         //later you decide you want to submit
         $(this).unbind('submit').submit()

  });
redsquare
  • 78,161
  • 20
  • 151
  • 159
  • Thanks for your answer, could you give me an example of how to do that. – Richbits Jul 22 '09 at 09:59
  • 3
    One of the best things to do is just call preventDefault() when you need to, based on conditionals. While this is the only real way to achieve exactly what you described, I encourage you to verify this is the best solution to your problem. :) – Swivel Nov 15 '12 at 21:33
  • Great answer but only works because it implies that you will navigate away from the page and you will never need to handle the event again - so not applicable to other events really. Still, great work :) – James Westgate Jan 11 '14 at 22:09
  • @JamesWestgate Surely you could just add an extra line to re-bind after you trigger the event in that case. – Casey Sep 10 '14 at 20:00
  • @Swivelgames Yes, except that if your check doesn't execute fast enough the form gets submitted and you get redirected before you ever get to the line where you call event.preventDefault(). – Casey Sep 10 '14 at 20:01
  • @emodendroket I'm not entirely sure if this is accurate. Afterall, iirc, you can still `return false` to simulate `e.preventDefault();`. However, I am talking about JavaScript in general. jQuery probably simply runs `callback.call( ... )`, instead of executing `return callback.call( ... )`. In which case, you would absolutely be correct in saying that execution might not be fast enough. In which case, that could potentially introduce an issue where `e.preventDefault` doesn't even execute in time (albeit, that'd be a considerably notable achievement if it ever actually occurred). – Swivel Sep 17 '14 at 20:48
  • 1
    @Swivelgames OK, but what I mean is, like, `if (someLongRunningOperation()) {e.preventDefault();}` can definitely fail for that reason; I debugged this very issue myself shortly before writing my comment. – Casey Sep 18 '14 at 00:02
15

Either you do what redsquare proposes with this code:

function preventDefault(e) {
    e.preventDefault();
}
$("form").bind("submit", preventDefault);

// later, now switching back
$("form#foo").unbind("submit", preventDefault);

Or you assign a form attribute whenever submission is allowed. Something like this:

function preventDefault(e) {
    if (event.currentTarget.allowDefault) {
        return;
    }
    e.preventDefault();
}
$("form").bind("submit", preventDefault);

// later, now allowing submissions on the form
$("form#foo").get(0).allowDefault = true;
Patrice Neff
  • 1,444
  • 11
  • 13
  • Awewsome simple solution! This solved my problem of switching on/off iOS default behaviour for elastic body scrolling and keeping some elements scrollable. Cool! – Garavani Sep 04 '14 at 07:45
9
function(e){ e.preventDefault();

and its opposite

function(e){ return true; }

cheers!

foxybagga
  • 4,184
  • 2
  • 34
  • 31
  • 1
    One problem, which is that if whatever you want to do takes too long (e.g., make an Ajax call) you may never reach "return false" or "e.preventDefault()" if you put it after the conditional. – Casey Sep 10 '14 at 19:40
2
$('form').submit( function(e){

     e.preventDefault();

     //later you decide you want to submit
     $(this).trigger('submit');     or     $(this).trigger('anyEvent');
adardesign
  • 33,973
  • 15
  • 62
  • 84
1

With async actions (timers, ajax) you can override the property isDefaultPrevented like this:

$('a').click(function(evt){
  e.preventDefault();

  // in async handler (ajax/timer) do these actions:
  setTimeout(function(){
    // override prevented flag to prevent jquery from discarding event
    evt.isDefaultPrevented = function(){ return false; }
    // retrigger with the exactly same event data
    $(this).trigger(evt);
  }, 1000);
}

This is most complete way of retriggering the event with the exactly same data.

Tomislav Simić
  • 207
  • 2
  • 8
1

I had a similar problem recently. I had a form and PHP function that to be run once the form is submitted. However, I needed to run a javascript first.

        // This variable is used in order to determine if we already did our js fun
        var window.alreadyClicked = "NO"
        $("form:not('#press')").bind("submit", function(e){
            // Check if we already run js part
            if(window.alreadyClicked == "NO"){
                // Prevent page refresh
                e.preventDefault();
                // Change variable value so next time we submit the form the js wont run
                window.alreadyClicked = "YES"
                // Here is your actual js you need to run before doing the php part
                xxxxxxxxxx

                // Submit the form again but since we changed the value of our variable js wont be run and page can reload (and php can do whatever you told it to)
                $("form:not('#press')").submit()
            } 
        });
-3

You can re-activate the actions by adding

this.delegateEvents();  // Re-activates the events for all the buttons

If you add it to the render function of a backbone js view, then you can use event.preventDefault() as required.