How can I handle a form submission without the page reloading?
Quick answer
Listen for the form’s submit event, then call event.preventDefault() inside the handler if your page will handle the submission itself. This cancels the browser’s default form action, which may otherwise navigate or submit in the browser’s usual way. Preventing that action does not provide your submission logic: add your own handling, or leave the default action in place. [S1][S2]
The question, the details, the next step.
A practical checklist
Select the form, not just a button.
Add a listener for the form’s
submitevent.Call
event.preventDefault()only when your page will handle the submission.Add the actual page-specific handling for submitted values.
Check that the result matches whether you intend to handle the submission or use the browser’s default action.
A few more useful answers
Will `preventDefault()` stop every form submission?
What should I put in the handler after calling `preventDefault()`?
Add the handling your page needs, such as displaying a message or using your application’s submission logic. The example only updates text; it does not send form data.
Can I leave out `preventDefault()`?
Yes. Leave it out if you want the browser’s default form submission behavior rather than taking over the submission in page code. [S1]
Sources
References used for this guide.
- [S1] HTMLFormElement: submit event — Web APIs | MDN developer.mozilla.org · Checked
- [S2] Event — Web APIs | MDN developer.mozilla.org · Checked
