jQuery <input> is Empty via val()

Introduction

You can use the val() method to test or check if inputs are empty.

View in separate window

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Check If Input Text Box has Empty Value in jQuery</title>
<style>
    .error{/*from w w w .ja v  a 2  s  .  c om*/
        outline: 1px solid red;
    }
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function(){
    $('#myForm input[type="text"]').blur(function(){
        if(!$(this).val()){
            $(this).addClass("error");
        } else{
            $(this).removeClass("error");
        }
    });
});
</script>
</head>
<body>
    <form id="myForm">
        <p><label>First Name: <input type="text"></label></p>
        <p><label>Last Name: <input type="text"></label></p>
        <p><label>Email Address: <input type="text"></label></p>
    </form>
</body>
</html>



PreviousNext

Related