Account
Categories

JavaScript onblur Event: Field Exit


Definition

If you use this event on a field in a form, it can check the data, show a message, or validate the input after the user exits the field.

It works when the user leaves a form box (like Name, Email, or Message)

Developers use it to ensure the user fills the form correctly and to detect errors immediately.

Now you will clearly understand with the help of the flowchart.

Start
   |
   v
Create Form (Name, Contact, Email, Message)
   |
   v
Add onblur Function --> [This function runs when the user leaves a field]
   |
   v
User types in a field
   |
   v
User moves out of the field
   |
   v
onblur Function runs
   |
   |-- Is it the Name field? --> Check value or show message
   |-- Is it a Contact field? --> Check value or show message
   |-- Is it an Email field? --> Check value or show message
   |-- Is it a Message field? --> Check value or show message
   |
All checked --> User moves to next field or submits form.
   |
   v
End
  

In HTML, Syntax:

<input type="text" onblur="functionName()">

Example:

<input type="text" onblur="checkField()">

In JavaScript, Syntax:

document.getElementById("fieldId").onblur = functionName;

Example:

document.getElementById("name").onblur = function() {
    alert("You left the Name field!");
};