Check if input is empty on blur with jQuery
In this tutorial we are going to show you how to check on blur if an <input>
is empty with jQuery. Short explanation: When you leave a text-field after clicking inside it you blur it. When you click inside a text-field you focus it.
Demo
HTML
jQuery
$(document).ready(function(){
$('input[name=test]').blur(function(){
if($(this).val().length == 0){
alert("Input is empty!");
}});
});
Explanation
First of all we ask whether the document is ready and all elements are loaded. When the document is loaded a function should take action.
$(document).ready(function(){
});
Now we select our <input>
and assign a function to this input as soon as the user has blurred it (you blur a text field when you leave it).
$(document).ready(function(){
$('input[name=test]').blur(function(){
});
});
In our function we ask whether the text field is empty or not. If it's empty a warning window containing the text "Input is empty!" should appear.
$(document).ready(function(){
$('input[name=test]').blur(function(){
if($(this).val().length == 0){
alert("Input is empty!");
}});
});