jQuery Event preventDefault() Method



The jQuery event preventDefault() method is used to prevent (or stop) the default action of an element from being executed. You can use this method when you want to prevent a browser from executing its default behavior, such as submitting a form when a submit button is clicked or following a link’s URL when it is clicked.

You can use another method named isDefaultPrevented() to know whether this method was ever called (on that event object).

Syntax

Following is the syntax of the jQuery event preventDefault() method −

event.preventDefault()

Parameters

This method does not accept any parameter.

Return Value

This method does not have any return value.

Example 1

The following is the basic example of the jQuery event preventDefault() method −

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
    <p>Click on the following link to redirect to another page: </p>
    <a href="https://www.tutorialspoint.com/index.htm">TutorialsPoint</a>
    <span></span>
    <script>
        $('a').click(function(event){
            event.preventDefault();
            alert("Default behaviour is disabled");
            $('span').text("The redirection will not occur because it has been prevented")
            $('span').css("color", "red");
        });
    </script>
</body>
</html>

Output

The above program displays a link. When the user clicks on the link, a pop-up alert will appear on the browser screen, indicating that redirection to another page is not allowed −


Example 2

Following is another example of the jQuery event preventDefault() method. We use this method to prevent the form submission when user submit the form −

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <style>
        form, input, button {
            display: block;
        }
        form input, button {
            padding: 10px;
            margin: 10px 0px;
        }
    </style>
</head>
<body>
    <form>
        Username: <input type="text" placeholder="Username" name="username">
        Password: <input type="password" placeholder="Password">
        <button type="submit">Login</button>
    </form>
    <script>
        $('form').submit(function(event) {
            event.preventDefault();
            alert("Form can't be submitted");
        });
    </script>
</body>
</html>

Output

After executing the above program, a form will be created having two input fields and a button, when the user tries to submit the form a pop-up alert will appear on the browser screen indicating that the form can't be submitted −


jquery_ref_events.htm
Advertisements