Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

e.preventDefault prevent click

Tags:

jquery

I have the following code to just test how the e.preventDefault() works. I would think it would stop the click event from happening.

     $(document).ready(function( )
     {

       $("button").click(function(e)
       {

         e.preventDefault();  

          alert('button clicked');

       });

      });

I have a button. What is the purpose of e.preventDefault(). From what I read, it will prevent the action which in this case is the click.

Note that in the above example, the alert message still show. How does e.preventDefault() work for a button click. I know if it was a hyperlink, it would prevent the hyperlink from going to it target.

like image 567
Nate Pet Avatar asked Nov 15 '25 02:11

Nate Pet


1 Answers

preventDefault is to prevent default, browser action. So if you will put something like:

$("a").click(function(e){e.preventDefault();})

click on links will do nothing. Or on submit button - form won't be submitted

like image 155
Viktor S. Avatar answered Nov 17 '25 22:11

Viktor S.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!