Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
How can I prevent a form from submitting when a button is clicked in JavaScript?
Asked on Mar 31, 2026
Answer
To prevent a form from submitting when a button is clicked, you can use JavaScript to intercept the form's submit event and call the `preventDefault` method.
<!-- BEGIN COPY / PASTE -->
<form id="myForm">
<button type="submit">Submit</button>
</form>
<script>
document.getElementById("myForm").addEventListener("submit", function(event) {
event.preventDefault();
alert("Form submission prevented!");
});
</script>
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The `addEventListener` method is used to attach an event handler to the form's "submit" event.
- The `preventDefault` method is called on the event object to stop the form from submitting.
- An alert is shown to confirm that the form submission was prevented. You can replace this with any other logic you need.
- Ensure the button within the form has a type of "submit" to trigger the form's submit event.
Recommended Links:
