Thursday, September 4, 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
32263 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6627 POSTS0 COMMENTS
Nicole Veronica
11799 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11857 POSTS0 COMMENTS
Shaida Kate Naidoo
6749 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6696 POSTS0 COMMENTS
Umr Jansen
6716 POSTS0 COMMENTS