The jQuery focusout method will occur when an element (most of the time an input) loses the user’s focus. This occurs when either the user mouse clicks away from that element, or tabs away from it using the keyboard.
$("input").focusout(function(){
//do something
});
Let’s say we have the following HTML:
To get the value that the user has entered for “Full Name”, we could use the jQuery focusout() method along with the val() method.
Once the user has typed a name and leaves the input field, the focusout method will be triggered.
$("#fname").focusout(function(){
var inputVal = $("#fname").val();
});
If you are using WordPress, don’t forget to change the $ to jQuery as below:
jQuery("#fname").focusout(function(){
var inputVal = jQuery("#fname").val();
});
This can also be done using the jQuery blur() method.
An Interactive Example of the jQuery focusout() Method
Below we will have a simple form with a name field and a submit button. One thing that is common in a lot of online forms is making sure actual information is entered before allowing the user to submit a form.
So below we will have a form that only lets you submit the information if you put in anything in the name field. If the user enters the name field but does not enter anything, we will display a warning to them. Here is the HTML code:
We will then use jQuery to disable or enable the submit button based on whether there is a string in the name field. We will do this using the length property. If the field is empty we will display a message using the insertAfter() method.
Finally, we will use the focusin() method to clear any previous warning messages so they don’t stack up.
Here is the code:
$("#fname").focusout(function(){
var inputVal = $("#fname").val();
if( inputVal.length != 0 ){
//The name field is NOT empty
$('button').prop('disabled', false);
} else {
//The name field IS empty
$('button').prop('disabled', true);
$('Make sure to enter a name!
').insertAfter("#fname");
}
});
$("#fname").focusin(function(){
$('#no-name').remove();
});
The final code and output for this example is below.
Make sure to click the form field and click away with nothing in it to see the full example.
Code Output:
Full Code:
<script>
$("#fname").focusout(function(){
var inputVal = $("#fname").val();
if( inputVal.length != 0 ){
//The name field is NOT empty
$('button').prop('disabled', false);
} else {
//The name field IS empty
$('button').prop('disabled', true);
$('Make sure to enter a name!
').insertAfter("#fname");
}
});
$("#fname").focusin(function(){
$('#no-name').remove();
});
</script>
Hopefully this article has been useful to help you understand how to use the jQuery focusout() method.