New Page 1

This page discusses - New Page 1

New Page 1

JavaScript blur event

       

When any text box, text area or select box looses its focus then the blur event occurs. The onBlur event handler can execute the specific JavaScript code on the invocation of a blur event. To explain this onBlur event handler, we have created a simple example here which will provide you the clear understanding of blur event.

Explanation with code :

In this example we have created three text boxes for First name, Middle name and Last name and as soon as we lost focus from the text box, onBlur() event occurs and specified function or methods is invoked. Here we have created three function which are invoked on the blur event of the given three input text boxes.


0    
function addFName() {
 alert("First name blurred");
 document.getElementById("fname").value="Satya";
  }
  function addMName() {
  alert("Middle name blurred");
  document.getElementById("mname").value="Kumar";
  }
  function addLName() {
 alert("Last name blurred");
 document.getElementById("lname").value="Patel";
  }

Function addFName() is called on the blur event of first text box ( first name), function addMName() is called on the blur event of the second text field (middle name) and addLName() function is called on blur event of third text field ( last name ). 

<input type="text" value="" id="fname" onBlur=addFName()>

As you can see from the above code that we have invoked the addFName() method on the blur event Here is the full source code as follows :

<html>
  <head>
  <title>
  </title>
  <script language="javascript" >
  function addFName() {
 alert("First name blurred");
 document.getElementById("fname").value="Satya";
  }
  function addMName() {
  alert("Middle name blurred");
  document.getElementById("mname").value="Kumar";
  }
  function addLName() {
 alert("Last name blurred");
 document.getElementById("lname").value="Patel";
  }
  </script>
  </head>
  <body>
  <div style="background: #DFDFFF; width:'100%';" align="center">
  <font color="#000080" size="12pt">
  <b>JavaScript Blur Event Example</b>
  </font>
  </div>
  <p>&nbsp;</p>
  Enter First Name <input type="text" value="" id="fname" 
   
onBlur="addFName()"><br>
  Enter Middle Name <input type="text" value="" id="mname"
    
onBlur="addMName()"><br>
  Enter Last Name <input type="text" value="" id="lname"
    
onBlur="addLName()"><br>
  </body>
</html>

Output :

As soon as we lost focus from the very first text box it calls the "onBlur" event and an alert message floats showing "First name blurred" message.

As we click on the "Ok" button of alert message box it writes text into the first text box and focus goes on the second text box.

As we move the focus from the second text box it again floats an alert message.

You can also download source code from the following link :

Download Source Code