DEV Community

Adnan Afzal
Adnan Afzal

Posted on

2 methods to prevent form from submission

Normally, when you submit the form, it redirects to the action attribute link. But you can stop that reload and call an AJAX or any other Javascript function.

1. preventDefault

You can call the preventDefault function on the event target and it will stop the form from redirecting to the page specified in the action attribute of the <form> tag.

<form method="POST" action="your-page.php" onsubmit="onFormSubmit();">
    <input type="submit" />
</form>
Enter fullscreen mode Exit fullscreen mode

Then you can create the following Javascript function to prevent the page reload:

function onFormSubmit() {
    event.preventDefault();

    // your Javascript code here
}
Enter fullscreen mode Exit fullscreen mode

In this method, the form is first prevented from submission and then your Javascript code will be run.

2. return false

The second approach is to use the return false statement in your Javascript code. For this, you also need to return the value from onsubmit event function. Let's check this out.

<form method="POST" action="your-page.php" onsubmit="return onFormSubmit();">
    <input type="submit" />
</form>
Enter fullscreen mode Exit fullscreen mode

Then create your Javascript function as like that:

function onFormSubmit() {
    // your Javascript code here

    return false;
}
Enter fullscreen mode Exit fullscreen mode

In this method, your Javascript code runs first before preventing the form submission.

Recommendation

We would recommend the 1st method i.e. preventDefault because it is the very first line of the Javascript function. So if there is an error in your Javascript code, your browser will not get reloaded and thus you will be able to view the error in the browser console.

Top comments (0)