Q:

How to Check If an Input Field is Empty Using jQuery

0

How to Check If an Input Field is Empty Using jQuery

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the jQuery val() Method

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

The following example will add a red outline around the inputs if it is focused but not filled out.

<!DOCTYPE html>
<html lang="en">
<head>
<title>Check If Inputs are Empty using jQuery</title>
<style>
    .error{
        outline: 1px solid red;
    }    
</style>
<script src="https://code.jquery.com/jquery-3.5.1.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>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Get the Children of the $(this) Selector in... >>
<< How to forEach Over an Array in JavaScript...