Monday, October 6, 2025
HomeLanguagesJavascriptpreventDefault() Event Method

preventDefault() Event Method

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-

RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32338 POSTS0 COMMENTS
Milvus
86 POSTS0 COMMENTS
Nango Kala
6707 POSTS0 COMMENTS
Nicole Veronica
11871 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11936 POSTS0 COMMENTS
Shaida Kate Naidoo
6825 POSTS0 COMMENTS
Ted Musemwa
7089 POSTS0 COMMENTS
Thapelo Manthata
6779 POSTS0 COMMENTS
Umr Jansen
6780 POSTS0 COMMENTS