Open In App

preventDefault() Event Method

Improve
Improve
Like Article
Like
Save
Share
Report

The preventDefault() method is used to prevent the browser from executing the default action of the selected element. It can prevent the user from processing the request by clicking the link.
Syntax:

event.preventDefault()

Parameters: It does not accept any parameter.
The event is used to denote the event or action by the user in the response of which the method works.

jQuery code to show the working of the preventDefault() function:

Code #1:
This code will prevents the browser from going to another page.




<html>
      <head>
            <title>GEEKSFORGEEKS ARTICLE<title/>
                <!-- INCLUDE THE JQUERY CDN -->
                <script src="https://ajax.googleapis.com/ajax/
                libs/jquery/3.3.1/jquery.min.js"></script>
            <script type="text/javascript">
               $(document).ready(function()
                {    
              $("a").click(function(event)
               {            
                event.preventDefault();
                alert("prevented");
               });
                });
             </script>
    </head>
    <body>
        <p>Click the link:</p>
           <a href="https://www.google.com">GOOGLE</a>
    </body>
</html>


Output:
It shows the output like given below-

Code #2:
This code will prevent the browser from redirecting the page to another PHP file.




<html>
         <head>
             <title>GEEKSFORGEEKS ARTICLE<title/>
        <script src="https://ajax.googleapis.com/ajax/
             libs/jquery/3.3.1/jquery.min.js"></script>
           <script type="text/javascript">
              $(document).ready(function()
               {    
              $("#submit").click(function(event)
               {            
                event.preventDefault();
                alert("ACTION IS PREVENTED");
                });
                });
            </script>
    </head>
    <body>
       <form action="submit.php">
            <input type="text" placeholder="enter username">
            <input id="submit" type="submit" name="submit">
       </form>
    </body>
</html>


Output:
It shows the output like given below-



Last Updated : 18 Jan, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads