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.

JavascriptForm Validation

Code

snippet
// 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,提交时校验挂 change

How 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

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.