Undoing Default Action in jQuery
As you should already know, a user action in JavaScript is cancelled using event.preventDefault()
. Let's prevent the form data from being submitted, as well as the event from bubbling further:
$('form').on('submit', function(event) {
event.preventDefault();
});
You can also prevent just the form submission (but not the event bubbling) in jQuery style by having your event handler function return false
:
$('form').on('submit', function() {
return false;
});
Of course, you can cancel any event, such as a click on a link. For example, we have the following link in the HTML code:
<a href="/">link</a>
Now let's use undo:
$('a').on('click', function () {
alert('You cannot follow this link!');
return false;
});