JavaScript and forms
Handle the submit event
Listen for form submission at the form level, prevent the default only when needed, and preserve native behavior when JavaScript fails.
8 minute lesson
Listen to the form’s submit event, not only a button click.
const form = document.querySelector('form')
form.addEventListener('submit', event => {
event.preventDefault()
const data = event.submitter
? new FormData(form, event.submitter)
: new FormData(form)
console.log([...data])
})
The submit event covers pointer clicks, keyboard submission, and different submit buttons. A click listener on one button misses some of those paths.
Call preventDefault() only when JavaScript will complete the submission another way. Without it, the browser follows the form’s normal action and method. That native behavior is a useful baseline.
Keep the HTML complete:
<form action="/feedback" method="post">
<!-- labeled controls -->
<button type="submit">Send feedback</button>
</form>
If the script fails to load, the form still reaches the server. JavaScript can enhance the interaction with inline results, but it should not be the only place that knows the endpoint.
Do not skip server validation because form.checkValidity() passed. The event handler runs in a client the visitor controls.
Add two named submit buttons and log event.submitter. Then submit once by click and once with the keyboard. Check which button value appears in FormData.
Lesson completed