SyntaxStudy
Sign Up
JavaScript Form Events: submit, change, input, focus, blur
JavaScript Beginner 7 min read

Form Events: submit, change, input, focus, blur

Form Events

HTML forms generate a rich set of events that you can intercept to validate input, provide real-time feedback, and handle submission without a page reload. Mastering form events is essential for building interactive web applications.

submit

The submit event fires on the <form> element when the user submits the form. Call event.preventDefault() to prevent the default browser navigation and handle the submission with JavaScript instead.

input and change

input fires immediately on every keystroke or value change. change fires when the element loses focus after its value has changed, or for checkboxes and selects, immediately on selection. Use input for live feedback and change for final-value processing.

focus and blur

focus fires when an element gains focus; blur fires when it loses focus. Neither event bubbles, but their bubbling counterparts focusin and focusout do. Use focus/blur to show/hide labels or validate fields on departure.

Example
const form = document.querySelector('form');
const emailInput = document.querySelector('#email');
form.addEventListener('submit', function(e) {
  e.preventDefault();
  const data = new FormData(form);
  console.log(Object.fromEntries(data));
});
emailInput.addEventListener('input', function() {
  console.log('Live value:', this.value);
});
emailInput.addEventListener('change', function() {
  console.log('Changed to:', this.value);
});
emailInput.addEventListener('focus', () => {
  emailInput.style.outline = '2px solid blue';
});
emailInput.addEventListener('blur', () => {
  emailInput.style.outline = '';
});
Pro Tip

Always call event.preventDefault() on form submit events when handling forms with JavaScript — without it, the browser will navigate away from the page before your handler can process the data.