Sikret Miseon
Sikret Miseon

Reputation: 557

jquery clarification regarding preventDefault

http://api.jquery.com/event.preventDefault/

"If this method is called, the default action of the event will not be triggered."

"default action" means redirecting people from a different page when they click a hyperlink, as far as i observed in sample code.

is there any other use for this function?

how does it interact with forms?

Upvotes: 4

Views: 158

Answers (4)

Muhammad Usman
Muhammad Usman

Reputation: 12503

preventDefault() prevents any default action of browser or so for the specified event.

There are many practical use of preventDefault(), I have summarized a few for you. You will also find the answer to your question about forms within this.

It prevents:

  • Submitting form while clicking submit button
  • Submitting form while pressing enter
  • Sometimes it can also prevent scrolling
  • Keypress actions also.
  • Right click browser menu
  • Opening new tabs while clicking middle button on link
  • Opening links while clicking left button, as you mentioned,

And there are many

Upvotes: 1

ipr101
ipr101

Reputation: 24236

preventDefault will prevent the default event occuring, so, for example, if we linked the following code to a form -

$('#form').submit(function(e) {
  alert('Handler for .submit() called.');
  e.preventDefault();
});

The e.preventDefault() call will prevent the form being submitted as that is the default event that would normally occur on a form submit.

Upvotes: 2

James Allardice
James Allardice

Reputation: 165971

As you said, preventDefault prevents the default action of the event from being triggered. The default action of the event depends on the type of event, and the event target.

For example, if preventDefault was used in a click event handler for a checkbox, the checkbox would not become checked upon click. If it was used in a keydown event handler for an text input, the pressed key would not be written to the input value. If it was used in a submit event handler for a form, it would prevent the form from submitting.

Basically, it stops any event from performing the action it would perform by default.

Upvotes: 4

David Thomas
David Thomas

Reputation: 253308

It prevents the default action of the element, whatever that default action might be.

In the case of forms and inputs, in response to a click or such, it would prevent checking a radio-button or checkbox, it would prevent the submission of the form (or whatever action was specified) when clicking the submit button.

Upvotes: 1

Related Questions