Form Events in JavaScript
Handle form events in JavaScript: submit with preventDefault, input vs change, focus and blur, checkbox, radio, reset and invalid. Explanation and output.
This code needs a web page. Add the HTML elements it looks up by id, link the script, and open the page in a browser. Node has no document object. Add a #myForm with #email and #password fields, plus #myInput, #mySelect, #myCheckbox, radio inputs and #myTextarea.
1// Method 1: Form submission2const form = document.getElementById('myForm');34form.addEventListener('submit', function(e) {5 e.preventDefault(); // Prevent default submission6 console.log('Form submitted');78 const formData = new FormData(form);9 console.log('Form data:', Object.fromEntries(formData));10});1112// Method 2: Input events13const input = document.getElementById('myInput');1415input.addEventListener('input', function(e) {16 console.log('Input value:', e.target.value);17});1819input.addEventListener('change', function(e) {20 console.log('Value changed:', e.target.value);21});2223input.addEventListener('focus', function(e) {24 console.log('Input focused');25 e.target.style.borderColor = 'blue';26});2728input.addEventListener('blur', function(e) {29 console.log('Input blurred');30 e.target.style.borderColor = '';31 // Validate on blur32 validateInput(e.target);33});3435// Method 3: Real-time validation36input.addEventListener('input', function(e) {37 const value = e.target.value;38 if (value.length < 3) {39 e.target.setCustomValidity('Must be at least 3 characters');40 } else {41 e.target.setCustomValidity('');42 }43});4445// Method 4: Select element46const select = document.getElementById('mySelect');4748select.addEventListener('change', function(e) {49 console.log('Selected:', e.target.value);50});5152// Method 5: Checkbox53const checkbox = document.getElementById('myCheckbox');5455checkbox.addEventListener('change', function(e) {56 console.log('Checked:', e.target.checked);57});5859// Method 6: Radio buttons60const radios = document.querySelectorAll('input[type="radio"]');6162radios.forEach(radio => {63 radio.addEventListener('change', function(e) {64 if (e.target.checked) {65 console.log('Selected:', e.target.value);66 }67 });68});6970// Method 7: Textarea71const textarea = document.getElementById('myTextarea');7273textarea.addEventListener('input', function(e) {74 const length = e.target.value.length;75 console.log('Character count:', length);7677 if (length > 100) {78 e.target.style.color = 'red';79 } else {80 e.target.style.color = '';81 }82});8384// Method 8: Form validation85form.addEventListener('submit', function(e) {86 e.preventDefault();8788 const email = form.querySelector('#email').value;89 const password = form.querySelector('#password').value;9091 if (!email.includes('@')) {92 alert('Invalid email');93 return;94 }9596 if (password.length < 8) {97 alert('Password must be at least 8 characters');98 return;99 }100101 console.log('Form is valid');102 // Submit form103});104105// Method 9: Reset event106form.addEventListener('reset', function(e) {107 console.log('Form reset');108});109110// Method 10: Invalid event111input.addEventListener('invalid', function(e) {112 e.preventDefault();113 console.log('Invalid input');114 showError(e.target, 'Please enter a valid value');115});
Sample Output
Value changed: Ravi
change fires once, when the field loses focus.
Form data: {...}FormData only includes fields that have a name attribute.
In this one
- How to stop a form reload with preventDefault
- The difference between input and change
- How focus and blur help validation
- How to collect values with FormData
How it works
- 1
submit is caught and form data is logged as an object.
- 2
input logs each keystroke and change logs the final value.
- 3
focus and blur style the field and validate it.
- 4
select, checkbox, radio and textarea log their values.
- 5
A second submit handler checks the email and password.
- 6
reset and invalid events log their messages.
Edge cases
Placeholder functions
validateInput and showError are not defined.
Write them before running, or the blur and invalid handlers throw.
Two submit handlers
Both run on every submit.
Method 1 always logs data, even when Method 8 finds an error. Merge them in real code.
Client-side checks only
Users can bypass JavaScript validation.
Always validate again on the server.
What's going on
Forms are how users send data, like a college admission form or a feedback box. Form events let you check and react to what they type.
submit fires when the form is sent. By default the browser reloads or moves to a new page. e.preventDefault() stops that so JavaScript can handle the data. new FormData(form) collects all named fields, and Object.fromEntries turns it into a plain object.
input fires on every change, in real time, as each letter is typed. change fires when the value is committed. For a text box that means when it loses focus, which is called blur. focus fires when a field becomes active. Method 2 uses focus and blur to colour the border, and calls validateInput on blur. validateInput is a placeholder for your own function.
Method 3 validates in real time. setCustomValidity sets a custom error message. An empty string means the field is valid again. This uses the browser's own HTML5 validation system.
Methods 4 to 7 cover other elements. A select dropdown and a checkbox use change. Checkbox gives checked, true or false. Radio buttons share a name, and you listen on each one. A textarea is multi-line text. Here it shows a live character count and turns red after 100 characters.
Method 8 does custom checks on submit: the email must contain @ and the password must be at least 8 characters. return stops the handler when a check fails.
reset fires when the form is cleared. invalid fires when HTML5 validation fails. Its preventDefault hides the browser bubble, and showError (another placeholder) shows your own message.
Best practices: prevent default on submit, validate on blur, show errors clearly, and use FormData to collect values.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Which event fires on every keystroke in a text input?
Pick an answer to check it.
Question 2
What stops a form from reloading the page?
Pick an answer to check it.
Questions people ask
When should I use input or change?
input for live feedback while typing. change for the final value.
Why does the page reload on submit?
That is the default form behaviour. Call e.preventDefault().
What is FormData?
A built-in object that reads all named fields of a form.