w3resource

jQuery: Attach a function to the blur event

jQuery Events : Exercise-2 with Solution

Attach a function to the blur event. The blur event occurs when the following <input> Field1 loses focus.
Sample Data :

HTML :

 <body>
 <form>
   <input id="field1" type="text" value="Field 1">
   <input id="field2" type="text" value="Field 2">
 </form>
</body>

Solution:

HTML Code :

<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
  <meta charset="utf-8">
  <title>jQuery: Attach a function to the blur event</title>
</head>
<body>
<form>
<input id="field1" type="text" value="Field 1">
<input id="field2" type="text" value="Field 2">
</form>
  <p>Write something in the input Field 1, and then click outside the field to check lose focus.</p>
</body>
</html>

JavaScript Code :

$( "#field1" ).blur(function() {
  alert( "Lose focus from Field1" );
});

Note : In jQuery blur( handler ) method is used to bind an event handler to the "blur" JavaScript event, or trigger that event on an element. It has the following parameter :

  • handler : A function to execute each time the event is triggered. [Type: Function( Event eventObject )]

Live Demo:

See the Pen jquery-events-exercise-2 by w3resource (@w3resource) on CodePen.


Contribute your code and comments through Disqus.

Previous: Attach a click and double-click event to the <p> element
Next: Append a <p> element with a text message when an <input> field is changed.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/jquery-exercises/jquery-events-exercise-2.php