- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to prevent buttons from submitting forms in HTML?
To prevent forms from being submitted, we can use the onsubmit property. We can also use the event.preventDefault() method −
- Prevent buttons from submitting forms using the onsubmit property
- Prevent buttons from submitting forms using event.preventDefault()
Prevent buttons from submitting forms using the onsubmit property
We can prevent form from submitting using the onsubmit property as shown below −
<form onsubmit="return false;">
We have returned false above in the <form> tag itself to prevent form from submitting.
Example
Let us see the complete example −
<!doctype html> <html lang="en"> <body> <h1>Details</h1> <form onsubmit="return false;"> <p>Select your preferred subject:</p> <div> <input type="radio" id="maths" name="subject" value="maths"> <label for="maths">Maths</label> <input type="radio" id="science" name="subject" value="science"> <label for="science">Science</label> <input type="radio" id="english" name="subject" value="english"> <label for="english">English</label> </div><br> <div> <button id="submit" type="submit">Submit</button> </div> </form> </body> </html>
Output
Select any Subject radio button above and click Submit. It won’t get submitted −
Prevent buttons from submitting forms using event.preventDefault()
We can prevent form from submitting using the event.preventDefault() method −
<form onsubmit="event.preventDefault();">
Example
Let us now see the complete example −
<!doctype html> <html lang="en"> <body> <h1>Details</h1> <form onsubmit="event.preventDefault();"> <p>Select your preferred subject:</p> <div> <input type="radio" id="maths" name="subject" value="maths"> <label for="maths">Maths</label> <input type="radio" id="science" name="subject" value="science"> <label for="science">Science</label> <input type="radio" id="english" name="subject" value="english"> <label for="english">English</label> </div><br> <div> <button id="submit" type="submit">Submit</button> </div> </form> </body> </html>
Output
Select any Subject radio button above and click Submit. It won’t get submitted −
Advertisements