JavaScript AJAX Basics (retiring) jQuery and AJAX Posting Data with jQuery

When should you use event.preventDefault()?

I am not entirely sure when I should use this jQuery method.

There some places the browser has a default actions for some events on some elements. for example if you click on anchor element (link) it will take you to another page. to prevent such default actions you should use this method.

3 Answers

Steven Parker
Steven Parker
182,024 Points

:point_right: You would use this anytime something automatically happens and you want to stop it.

For example: a common use is when you attach a custom button-click handler to a form submit button. If your handler is validating the data and finds it unsuitable, it can use this to prevent the submit from actually happening.

Nicholas Pretorius
Nicholas Pretorius
18,666 Points

You can use it when there is a default behaviour for an HTML element. (https://api.jquery.com/event.preventDefault/) For example: when clicking a link, submitting a form, checking a check box etc.

I guess the most common use case would be when you want to bypass an action for some reason.

The DOM Web API has a similar method built in to use directly through JavaScript. https://developer.mozilla.org/en/docs/Web/API/Event/preventDefault

Is it always for default HTML behavior and nothing else?

Nicholas Pretorius
Nicholas Pretorius
18,666 Points

Going by the name of the function and the description of it, I would say yes.