Home Courses Input Field Events - onInput, onFocus, onBlur, KeyUp & KeyDown

Input Field Events - onInput, onFocus, onBlur, KeyUp & KeyDown

In JavaScript, events are actions performed by the user.

Examples:

  1. Clicking inside an input field
  2. Typing something
  3. Removing text
  4. 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:

  1. Take user input
  2. Validate input
  3. Show messages
  4. Update UI

All of this is handled using events.


Common Input Field Events

1. oninput

Triggered whenever the user types something


<input oninput="handleInputField(event)">

2. onkeydown

Triggered when a key is pressed


<input onkeydown="handleKeyDown()">

3. onkeyup

Triggered when the key is released


<input onkeyup="handleKeyUp()">

4. onfocus

Triggered when the input field gets focus (clicked)


<input onfocus="handleFocus()">

5. onblur

Triggered when the user clicks outside the input field


<input onblur="handleBlur(event)">


Event Object (Very Important)

When you pass the event:


function handleInputField(event){
console.log(event.target.value); // value
console.log(event.target.id); // id
console.log(event.target.name); // name
}

event.target gives complete details of the input field.


Using Same Function for Multiple Inputs


<input oninput="handleInputField(event)" id="age">
<input oninput="handleInputField(event)" id="email">

The same function handles both inputs.


Age Validation Example (Recommended Way)

Validation should be applied on blur (not on every key press):


function handleBlur(event){
console.log(event.target.name);

if(event.target.id === "age" && event.target.value <= 18){
alert("Not a valid age");
}
}


Important Fix in Your Code

You wrote:


if(event.target.id="age" && event.target.value<=18)

This is incorrect because it uses assignment.

Correct version:


if(event.target.id === "age" && event.target.value <= 18)

Use === for comparison, not =.


Event Flow (Order Example)

When a key is pressed:

  1. keydown
  2. input
  3. keyup


Final Working Code (Clean Version)

<input type="text"
oninput="handleInputField(event)"
onkeyup="handleKeyUp()"
onkeydown="handleKeyDown()"
onfocus="handleFocus()"
onblur="handleBlur(event)"
placeholder="enter name">

<input type="text"
oninput="handleInputField(event)"
onblur="handleBlur(event)"
name="userAge"
id="age"
placeholder="enter age">

<input type="text"
oninput="handleInputField(event)"
name="userEmail"
id="email"
placeholder="enter email">


Share this lesson: