The JavaScript onfocusout event 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.
Let’s say we have the following HTML:
To get the value that the user has entered for “Full Name”, we could use JavaScript along with the onfocusout event.
Once the user has typed a name and leaves the input field, the onfocusout event will be triggered, which will call the getValue() function. The function will use the value property to get the name entered by the user.
function getValue(){
var inputVal = document.getElementById("fname").value;
});
This can also be done using the jQuery focusout() method.
An Interactive Example of Using JavaScript with the onfocusout Event
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 the disabled property 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 show a hidden “p” element by changing its display property.
Finally, we will use the onfocus event to clear any previous warning messages so they don’t stack up.
Here is the code:
function getName(){
var inputVal = document.getElementById("fname").value;
if( inputVal.length != 0 ){
//The name field is NOT empty
document.getElementById("button1").disabled = false;
} else {
//The name field IS empty
document.getElementById("button1").disabled = true;
//Show the error message
document.getElementById("no-name").style.display = "block";
}
};
function clearMessages(){
//Hide the error message
document.getElementById("no-name").style.display = "none";
};
The final code and output for this example of using JavaScript with the onfocusout event 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>
function getName(){
var inputVal = document.getElementById("fname").value;
if( inputVal.length != 0 ){
document.getElementById("button1").disabled = false;
} else {
document.getElementById("button1").disabled = true;
document.getElementById("no-name").style.display = "block";
}
};
function clearMessages(){
document.getElementById("no-name").style.display = "none";
};
</script>
Hopefully this article has been useful to help you understand how to use JavaScript with the onfocusout event.