SubmitEvent Types Form Handlers
addEventListener("submit") infers SubmitEvent in TypeScript, so submitter and preventDefault arrive typed instead of as a loose Event parameter.
Code
const form = document.querySelector<HTMLFormElement>('#signup');
if (form) {
// submit 监听的 event 被推断为 SubmitEvent,而不是宽泛的 Event
form.addEventListener('submit', (event) => {
event.preventDefault();
// event.submitter 是触发提交的按钮,同样被正确推断
const data = new FormData(form);
const email = String(data.get('email') ?? '');
console.log('submitter:', event.submitter?.id ?? 'none');
console.log('email:', email);
});
}How the snippet works
Top-level bindings form hold the demo state — nothing sits inside a function scope.
Watch out for
documentexist only in browsers — a Node runtime has no shims for them out of the box.
Applying it
Output lines are prefixed (submitter:, email:), making each step’s effect easy to spot.
Statements that matter
form.addEventListener('submit', (event) => {
event.preventDefault();
// event.submitter 是触发提交的按钮,同样被正确推断
const data = new FormData(form);
const email = String(data.get('email') ?? '');
console.log('submitter:', event.submitter?.id ?? 'none');
console.log('email:', email);
});
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.
FAQ
- Does SubmitEvent Types Form Handlers run in plain Node.js?
- No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.