Input Field Events - onInput, onFocus, onBlur, KeyUp & KeyDown
In JavaScript, events are actions performed by the user.
Examples:
- Clicking inside an input field
- Typing something
- Removing text
- Clicking outside the field
All of these are called events.
Why Events are Important?
When you build real applications (login forms, signup forms, etc.), you need to:
- Take user input
- Validate input
- Show messages
- Update UI
All of this is handled using events.
Common Input Field Events
1. oninput
Triggered whenever the user types something
2. onkeydown
Triggered when a key is pressed
3. onkeyup
Triggered when the key is released
4. onfocus
Triggered when the input field gets focus (clicked)
5. onblur
Triggered when the user clicks outside the input field
Event Object (Very Important)
When you pass the event:
event.target gives complete details of the input field.
Using Same Function for Multiple Inputs
The same function handles both inputs.
Age Validation Example (Recommended Way)
Validation should be applied on blur (not on every key press):
Important Fix in Your Code
You wrote:
This is incorrect because it uses assignment.
Correct version:
Use === for comparison, not =.
Event Flow (Order Example)
When a key is pressed:
- keydown
- input
- keyup