Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

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.

BeginnerJavaScript Events ProgramsExample 7 of 10

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.

form-events.js
1// Method 1: Form submission
2const form = document.getElementById('myForm');
3
4form.addEventListener('submit', function(e) {
5 e.preventDefault(); // Prevent default submission
6 console.log('Form submitted');
7
8 const formData = new FormData(form);
9 console.log('Form data:', Object.fromEntries(formData));
10});
11
12// Method 2: Input events
13const input = document.getElementById('myInput');
14
15input.addEventListener('input', function(e) {
16 console.log('Input value:', e.target.value);
17});
18
19input.addEventListener('change', function(e) {
20 console.log('Value changed:', e.target.value);
21});
22
23input.addEventListener('focus', function(e) {
24 console.log('Input focused');
25 e.target.style.borderColor = 'blue';
26});
27
28input.addEventListener('blur', function(e) {
29 console.log('Input blurred');
30 e.target.style.borderColor = '';
31 // Validate on blur
32 validateInput(e.target);
33});
34
35// Method 3: Real-time validation
36input.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});
44
45// Method 4: Select element
46const select = document.getElementById('mySelect');
47
48select.addEventListener('change', function(e) {
49 console.log('Selected:', e.target.value);
50});
51
52// Method 5: Checkbox
53const checkbox = document.getElementById('myCheckbox');
54
55checkbox.addEventListener('change', function(e) {
56 console.log('Checked:', e.target.checked);
57});
58
59// Method 6: Radio buttons
60const radios = document.querySelectorAll('input[type="radio"]');
61
62radios.forEach(radio => {
63 radio.addEventListener('change', function(e) {
64 if (e.target.checked) {
65 console.log('Selected:', e.target.value);
66 }
67 });
68});
69
70// Method 7: Textarea
71const textarea = document.getElementById('myTextarea');
72
73textarea.addEventListener('input', function(e) {
74 const length = e.target.value.length;
75 console.log('Character count:', length);
76
77 if (length > 100) {
78 e.target.style.color = 'red';
79 } else {
80 e.target.style.color = '';
81 }
82});
83
84// Method 8: Form validation
85form.addEventListener('submit', function(e) {
86 e.preventDefault();
87
88 const email = form.querySelector('#email').value;
89 const password = form.querySelector('#password').value;
90
91 if (!email.includes('@')) {
92 alert('Invalid email');
93 return;
94 }
95
96 if (password.length < 8) {
97 alert('Password must be at least 8 characters');
98 return;
99 }
100
101 console.log('Form is valid');
102 // Submit form
103});
104
105// Method 9: Reset event
106form.addEventListener('reset', function(e) {
107 console.log('Form reset');
108});
109
110// Method 10: Invalid event
111input.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. 1

    submit is caught and form data is logged as an object.

  2. 2

    input logs each keystroke and change logs the final value.

  3. 3

    focus and blur style the field and validate it.

  4. 4

    select, checkbox, radio and textarea log their values.

  5. 5

    A second submit handler checks the email and password.

  6. 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.