input Fires Per Keystroke, change On Commit
input fires for every keystroke while change waits until the value commits on blur, so debounced search and final validation hook different events.
Code
// input 每次键入都触发;change 等到值提交(失焦或回车)才触发
const email = document.querySelector('#email');
email?.addEventListener('input', (event) => {
console.log('input ->', JSON.stringify(event.target?.value));
});
email?.addEventListener('change', (event) => {
console.log('change ->', JSON.stringify(event.target?.value));
});
email?.addEventListener('keydown', (event) => {
// 回车也会提交值、触发 change:preventDefault 只拦隐式表单提交,不拦事件
if (event.key === 'Enter') event.preventDefault();
});
// 用户键入 "a" 再 "b" 然后失焦,控制台依次是:
// input -> "a"、input -> "ab"、change -> "ab"
// 实时搜索挂 input,提交时校验挂 changeHow it works
Top-level bindings email hold the demo state — nothing sits inside a function scope.
What to watch for
- The snippet leans on
document— browser-only surfaces a bare Node process cannot provide.
Putting it to use
Output lines are prefixed (input ->, change ->), making each step’s effect easy to spot.
Core lines
email?.addEventListener('keydown', (event) => {
// 回车也会提交值、触发 change:preventDefault 只拦隐式表单提交,不拦事件
if (event.key === 'Enter') event.preventDefault();
});
email?.addEventListener('change', (event) => {
console.log('change ->', JSON.stringify(event.target?.value));
});
email?.addEventListener('input', (event) => {
console.log('input ->', JSON.stringify(event.target?.value));
});
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 input Fires Per Keystroke, change On Commit 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.