Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
Loading…
Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
Loading…
Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
JAVASCRIPT FORMS / CHAPTER 05 / Learn / LESSON 09
Theory. submit is an event of the form (not of the button). By default the browser sends the form and reloads the page. event.preventDefault() stops that and you take control.
The typical success path: preventDefault → read the fields → show a success message → form.reset() to clear. form.reset() sets each field back to its initial value (empty for a text field) and fires a reset event.
IMPORTANT ORDER: read the values first, then reset(). After reset() the fields are empty and your success text would have no data.
Small example:
form.addEventListener("submit", (event) => { event.preventDefault(); const note = form.elements.note.value; msg.textContent = "Saved: " + note; form.reset(); });
Code Lab has no network: the submission is simulated locally.
Common mistake: reset before reading; forgotten preventDefault; a click listener instead of submit (Enter in the field skips the click).
<form id="f"><input id="note" name="note" type="text"><button type="submit">Save</button></form><p id="msg"></p>preventDefault takes over the form; reset() returns the fields to the start — after you took the values.
Press Run — HTML loads in a sandbox iframe; Stop removes the iframe (also kills infinite loops).
›