JavaScript Interview Question #70
How do you handle form submission with JavaScript?
DOM, Events & Event Loop Fundamentals Mid-Level Intermediate
Quick Interview Answer
Listen for the form's submit event rather than relying only on a button's click event. The submit event also covers keyboard submission and other valid ways a form can be submitted.
Detailed Explanation
Listen for the form's submit event rather than relying only on a button's click event. The submit event also covers keyboard submission and other valid ways a form can be submitted.
If JavaScript will handle the request, call preventDefault, validate or collect the data, and then perform the required application operation. FormData provides a convenient way to read successful form controls.
Code Example
const form = document.querySelector("#profileForm");
form.addEventListener("submit", event => {
event.preventDefault();
const data = new FormData(form);
console.log(data.get("name"));
console.log(data.get("email"));
});