Handle form submission and reset
Quick answer
Listen to the form’s submit event rather than only a submit button click. This includes other native submission pathways. requestSubmit() acts like requesting submission with validation and a submit event; submit() bypasses interactive validation and the submit event. In local demos call preventDefault to avoid navigation. Reset restores default values, not necessarily empty values.
Browser examples
Run each snippet in a fresh browser document. These are static code blocks; ByteMind browser execution is not verified. Storage examples require a test origin.
const f=document.createElement("form"),i=document.createElement("input");i.required=true;i.setAttribute("aria-label","Name");f.append(i);document.body.append(f);let n=0;f.addEventListener("submit",e=>{e.preventDefault();n++;});f.requestSubmit();console.log(n);i.value="Ali";f.requestSubmit();console.log(n);Expected console output:
01Invalid required input prevents submit; valid input permits the canceled local submission.
const f=document.createElement("form"),i=document.createElement("input");i.defaultValue="original";f.append(i);i.value="edited";f.reset();console.log(i.value);Expected console output:
originalReset restores the control’s default value.
Common mistake
Do not use form.submit() when you intend to run normal submit handlers and constraint validation. Give non-submit buttons inside a form type="button".
Practice
Build a form with one labeled required field and one submit button; prevent navigation and report a successful local submission.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Handle form submission and reset — Knowledge Check
Apply the concept and predict the browser example behavior.
Which event should a form handler listen to for ordinary submission?
Which method requests submission with normal validation?
What value does reset restore to a text control?
What is the exact console output in Handle form submission and reset example 1?
const f=document.createElement("form"),i=document.createElement("input");i.required=true;i.setAttribute("aria-label","Name");f.append(i);document.body.append(f);let n=0;f.addEventListener("submit",e=>{e.preventDefault();n++;});f.requestSubmit();console.log(n);i.value="Ali";f.requestSubmit();console.log(n);What is the exact console output in Handle form submission and reset example 2?
const f=document.createElement("form"),i=document.createElement("input");i.defaultValue="original";f.append(i);i.value="edited";f.reset();console.log(i.value);