Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
How can I prevent default behavior for a form submission event in JavaScript? Pending Review
Asked on May 06, 2026
Answer
To prevent the default behavior of a form submission in JavaScript, you can use the "preventDefault" method on the event object within an event listener. This stops the form from submitting and allows you to handle the submission with custom logic.
<!-- BEGIN COPY / PASTE -->
document.querySelector("form").addEventListener("submit", function(event) {
event.preventDefault();
console.log("Form submission prevented.");
// Add custom form handling logic here
});
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The code attaches a "submit" event listener to a form element.
- "event.preventDefault()" stops the form from submitting in the traditional way.
- You can add your custom logic where indicated in the code.
- Ensure the form selector matches the form you want to target.
Recommended Links:
