59 Votes

jQuery: Undo event.preventDefault()

Question by SmartUser | Last update on 2020-10-18 | Created on 2012-07-22

In a submit form on my website, I use jQuery with event.preventDefault. However, I would allow later again, depending on the circumstances, that the form can be submitted.

Therefore, is it somehow possible to take back a preventDefault()?

ReplyPositiveNegativeDateVotes
1927 Votes

The function that you are looking for is called unbind().

Here is a small example:

$("#myform").submit(function(event) {
    event.preventDefault();
    // ...
});
 
// ...
 
$("#myform").unbind('submit');

First, we prevent using event.preventDefault(), that the form can be submitted, if we click on the submit button.

Then, we take this back with unbind('submit') and it works as before. Unbind ensures, that a preassigned event handler is canceled. In the example, we define with 'submit' the type of the event handler to be deleted. If you omit this and write $("#myform").unbind() instead, you will remove all assigned event handlers of the form.
Last update on 2020-10-18 | Created on 2012-07-22

ReplyPositive Negative
1822 Votes

And here is another way with the same effect:

var eventhandler = function(e) {
   e.preventDefault();      
}
      
$("#myform").bind('submit', eventhandler);
  
//...
  
$("#myform").unbind('submit', eventhandler);

This should also clarify the difference between bind() and unbind(). We are using bind() to assign an event handler and with unbind(), we remove it again. We have defined the event handler as a variable before, which has been assigned the function preventDefault.
Last update on 2020-10-18 | Created on 2012-07-23

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.