Forms and User Input
Listen for the submit event on the form, call preventDefault, then read values from the inputs (input.value) or with new FormData(form). Always trim and validate what the user typed.
Example
const form = document.createElement("form");
form.innerHTML = "<input name=\"name\" placeholder=\"Your name\"> <button>Greet</button>";
document.body.prepend(form);
form.addEventListener("submit", (event) => {
event.preventDefault();
const name = new FormData(form).get("name").trim();
document.getElementById("demo").textContent = name ? "Hello, " + name : "Please type a name";
});Exercise
Which event fires when a form is sent?
form.addEventListener("", handler);
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.