Check if inputs are empty using jQuery

Viewed 1375852

I have a form that I would like all fields to be filled in. If a field is clicked into and then not filled out, I would like to display a red background.

Here is my code:

$('#apply-form input').blur(function () {
  if ($('input:text').is(":empty")) {
    $(this).parents('p').addClass('warning');
  }
});

It applies the warning class regardless of the field being filled in or not.

What am I doing wrong?

22 Answers

The keyup event will detect if the user has cleared the box as well (i.e. backspace raises the event but backspace does not raise the keypress event in IE)

    $("#inputname").keyup(function() {

if (!this.value) {
    alert('The box is empty');
}});

how to check null undefined and empty in jquery

  $(document).on('input', '#amt', function(){
    let r1;
    let r2;
    r1 = $("#remittance_amt").val();
    if(r1 === undefined || r1 === null || r1 === '')
    {
      r1 = 0.00;
    }

    console.log(r1);
  });

You can try something like this:

$('#apply-form input[value!=""]').blur(function() {
    $(this).parents('p').addClass('warning');
});

It will apply .blur() event only to the inputs with empty values.

Great collection of answers, would like to add that you can also do this using the :placeholder-shown CSS selector. A little cleaner to use IMO, especially if you're already using jQ and have placeholders on your inputs.

if ($('input#cust-descrip').is(':placeholder-shown')) {
  console.log('Empty');
}

$('input#cust-descrip').on('blur', '', function(ev) {
  if (!$('input#cust-descrip').is(':placeholder-shown')) {
    console.log('Has Text!');
  }
  else {
    console.log('Empty!');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="text" class="form-control" id="cust-descrip" autocomplete="off" placeholder="Description">

You can also make use of the :valid and :invalid selectors if you have inputs that are required. You can use these selectors if you are using the required attribute on an input.

A clean CSS-only solution this would be:

input[type="radio"]:read-only {
        pointer-events: none;
}

Please use this code for input text

$('#search').on("input",function (e) {

});

if($("#textField").val()!=null)

this work for me

try this:

function empty(){
        if ($('.text').val().length == 0)
        {
            alert("field should not be empty");
        }
    }
Related