Jquery clarification regarding preventDefault

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

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

"default action" means redirecting people from another page when you click on the hyperlink, as far as I noticed in the code example.

is there any other use for this function?

How does it interact with forms?

+4
source share
4 answers

As you said, preventDefault prevents the event action from triggering by default. The default action of an event depends on the type of event and the purpose of the event.

For example, if preventDefault was used in the click event handler for a flag, the flag will not be checked on click. If it was used in the keydown event keydown to enter text, the key pressed would not be written to the input value. If it was used in the submit event handler for the form, this would prevent the form from submitting.

Basically, it stops any event from executing the action that it performed by default.

+4
source

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

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

Calling e.preventDefault() will prevent the form from submitting, as this is the default event that usually occurs on the submit form.

+2
source

It prevents the element from acting by default, no matter what it was by default.

In the case of forms and inputs, in response to a click or such, this will prevent the check box or check box from being checked, this will prevent the form (or any other action) from being submitted when the submit button is clicked.

+1
source

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

There is a lot of practical use to preventDefault() , I summed up a few for you. You will also find the answer to your question about forms in this.

This prevents:

  • Submitting a form when you click the submit button
  • Submitting a form when you press enter
  • Sometimes it can also prevent scrolling.
  • Key actions are also activated.
  • Right click on browser menu
  • Opening new tabs when you click the middle button on the link
  • Opening links when you click the left button, as you mentioned,

And there are many

+1
source

All Articles