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 in JavaScript?
Asked on Feb 15, 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 for the form's "submit" event.
<!-- BEGIN COPY / PASTE -->
const form = document.querySelector("form");
form.addEventListener("submit", function(event) {
event.preventDefault();
console.log("Form submission prevented.");
});
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The code selects a form element using "document.querySelector".
- An event listener is added to the form for the "submit" event.
- Inside the event listener, "event.preventDefault()" is called to stop the form from submitting.
- A console message is logged to indicate that the form submission was prevented.
Recommended Links:
