Prevent HTML <form> from being submitted with JavaScript/jQuery
This post will discuss how to prevent an HTML form from being submitted in JavaScript and jQuery.
The simplest solution to prevent the form submission is to return false on submit event handler defined using the onsubmit property in the HTML <form> element.
HTML
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<!doctype html> <html lang="en"> <body> <form onsubmit="return false;"> <p>Choose your preferred contact method:</p> <div> <input type="radio" id="email" name="contact" value="email"> <label for="email">Email</label> <input type="radio" id="phone" name="contact" value="phone"> <label for="phone">Phone</label> </div> <div> <button id="submit" type="submit">Submit</button> </div> </form> </body> </html> |
Alternatively, you can call the Event.preventDefault() to prevent the default action on a form submission from executing.
HTML
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<!doctype html> <html lang="en"> <body> <form onsubmit="event.preventDefault();"> <p>Choose your preferred contact method:</p> <div> <input type="radio" id="email" name="contact" value="email"> <label for="email">Email</label> <input type="radio" id="phone" name="contact" value="phone"> <label for="phone">Phone</label> </div> <div> <button id="submit" type="submit">Submit</button> </div> </form> </body> </html> |
Note that it is always a good practice to separate JavaScript from HTML markup, but the above solution fails to do so. A better solution is to bind an event handler to the “submit” JavaScript event. The submit event fires whenever the user submits a form.
JS
|
1 2 3 4 5 6 |
$(document).ready(function() { $('form').submit(function(e) { e.preventDefault(); // or return false; }); }); |
HTML
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<!doctype html> <html lang="en"> <body> <form> <p>Choose your preferred contact method:</p> <div> <input type="radio" id="email" name="contact" value="email"> <label for="email">Email</label> <input type="radio" id="phone" name="contact" value="phone"> <label for="phone">Phone</label> </div> <div> <button id="submit" type="submit">Submit</button> </div> </form> </body> </html> |
That’s all about preventing an HTML </form> from being submitted in JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)