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 22, 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 on the event object.
<!-- BEGIN COPY / PASTE -->
<form id="myForm">
<input type="text" name="example" placeholder="Type something">
<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 a "submit" event listener to the form.
- The `event.preventDefault()` method stops the form from submitting.
- You can add any additional logic inside the event listener function as needed.
- This approach ensures that the form's default submission behavior is halted.
Recommended Links:
