Check if inputs are empty using jQuery

Learn, how can we check whether the input field in a form in empty or not using jQuery?
Submitted by Pratishtha Saxena, on February 09, 2023

Checking if inputs are empty

Whenever we are looking to check if the element contains an appropriate value or text in it or if it is empty, we generally make use of the jQuery val() method. This will check whether the selected element has any values in it or not. Hence, we can manage all our further tasks and actions based on its result, which means that the element is empty or not.

jQuery val() Method

The val() method helps to get the value of the selected form field or the element. The element is specified by using the selector and following it the val() method is executed. It then returns the value specified for that element. Since majorly the value attribute is used for a form input field or a <select> tag, hence, the val() method is also used for those elements only.

Syntax:

$(selector).val();

This is a very simple method and does not take any parameters for returning the value of the selected element in jQuery.

Let's discuss this method in the following example where if the selected input field is empty, then a particular class is added as per the result. Otherwise, the class that was added before is removed respectively.

jQuery example to check if inputs are empty

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <title>Document</title>
    <style>
      .empty{
      background-color:yellow;
      }
    </style>
  </head>
  
  <body>
    <h2>Check if inputs are empty using jQuery</h2>
    <h4>Click the button to check which fields are empty.</h4>
    <button>Click Here</button> 
    <hr>
    <h3>Fill the FORM</h3>
    <form id="myForm">
      <label>Name: </label><input type="text"><br><br>
    </form>
    <hr>
    <h4 id="one"></h4>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
        $('button').click(function(){
                if(!$('input').val()){
                    $('input').addClass('empty');
                    $('h4#one').html('Field EMPTY !');
                }   
                else{
                    $('input').removeClass('empty');
                    $('h4#one').html('Field Already Filled!');
                }
            });
        });
  </script>
</html>

Output:

Example: Check if inputs are empty using jQuery



All jQuery Examples

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.