Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 994
Sikret Miseon Avatar asked Feb 23 '23 23:02

Sikret Miseon


2 Answers

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.

like image 122
James Allardice Avatar answered Mar 08 '23 14:03

James Allardice


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.

like image 37
ipr101 Avatar answered Mar 08 '23 14:03

ipr101