1 5 Votes

jQuery: Undo event.preventDefault()

Question by Guest | 22/07/2012 at 16:07

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

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

ReplyPositiveNegativeDateVotes

Progger99

Show Profile | Message
Avatar
1422 Votes

The function that you are looking for is called unbind(). Here is a small example:

$("#formx").submit(function(event) {
    event.preventDefault();
    // ...
});
 
// ...
 
$("#formx").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 $("#formX").unbind() instead, you will remove all assigned event handlers of the form.
22/07/2012 at 16:15

ReplyPositive Negative

Stefan Trost

Show Profile | Message
Avatar
1317 Votes

And here is another way with the same effect:

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

This should also clearify 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.
23/07/2012 at 23:25

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 articles on askingbox.com. How to do.