44 Views

21st August 2020

Jquery Check If Input Is Empty

How can I check if input is empty field is empty using jQuery?

Answers

30th December 2020

Answered by ravi sankar

Utilize the jQuery val() Method

You can utilize the val() method to test or else check if inputs remain empty within jQuery. The below example which will add a green outline around the inputs if it is focused but not filled.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Checking for Empty Value in jQuery</title>

<style>

    .error{

        outline: 1px solid yellow;

    }    

</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>Name: <input type="text"></label></p>

        <p><label>Position: <input type="text"></label></p>

        <p><label>Email Address: <input type="text"></label></p>

    </form>

</body>

</html>

Write your answer

GET STARTED

Speak with a Learning Advisor

Understand how the industry and practically oriented courses at Mindmajix transform your career.

  • Explore the trending and niche courses and learning maps
  • Learn about tuition fee, payment plans, and scholarships
  • Get access to webinars and self-paced learning videos