[jquery] Check if inputs are empty using jQuery

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?

This question is related to jquery validation

The answer is


<script type="text/javascript">
$('input:text, input:password, textarea').blur(function()
    {
          var check = $(this).val();
          if(check == '')
          {
                $(this).parent().addClass('ym-error');
          }
          else
          {
                $(this).parent().removeClass('ym-error');  
          }
    });
 </script>// :)

There is one other thing you might want to think about, Currently it can only add the warning class if it is empty, how about removing the class again when the form is not empty anymore.

like this:

$('#apply-form input').blur(function()
{
    if( !$(this).val() ) {
          $(this).parents('p').addClass('warning');
    } else if ($(this).val()) {
          $(this).parents('p').removeClass('warning');
    }
});

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.

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

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.


With HTML 5 we can use a new feature "required" the just add it to the tag which you want to be required like:

<input type='text' required>


Consider using the jQuery validation plugin instead. It may be slightly overkill for simple required fields, but it mature enough that it handles edge cases you haven't even thought of yet (nor would any of us until we ran into them).

You can tag the required fields with a class of "required", run a $('form').validate() in $(document).ready() and that's all it takes.

It's even hosted on the Microsoft CDN too, for speedy delivery: http://www.asp.net/ajaxlibrary/CDN.ashx


Please use this code for input text

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

});


$(function() {
  var fields = $('#search_form').serializeArray();
  is_blank = true;
  for (var i = 0; i < fields.length; i++) {
    // excluded fields
    if ((fields[i].name != "locale") && (fields[i].name != "utf8")) {
      if (fields[i].value) {
        is_blank = false;
      }
    }
  }
  if (is_blank) {
    $('#filters-button').append(': OFF');
  }
  else {
    $('#filters-button').append(': ON');
  }
});

Check if all fields are empty and append ON or OFF on Filter_button


_x000D_
_x000D_
function checkForm() {_x000D_
  return $('input[type=text]').filter(function () {_x000D_
    return $(this).val().length === 0;_x000D_
  }).length;_x000D_
}
_x000D_
_x000D_
_x000D_


you can use also..

$('#apply-form input').blur(function()
{
    if( $(this).val() == '' ) {
          $(this).parents('p').addClass('warning');
    }
});

if you have doubt about spaces,then try..

$('#apply-form input').blur(function()
{
    if( $(this).val().trim() == '' ) {
          $(this).parents('p').addClass('warning');
    }
});

A clean CSS-only solution this would be:

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

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.


how come nobody mentioned

$(this).filter('[value=]').addClass('warning');

seems more jquery-like to me


Doing it on blur is too limited. It assumes there was focus on the form field, so I prefer to do it on submit, and map through the input. After years of dealing with fancy blur, focus, etc. tricks, keeping things simpler will yield more usability where it counts.

$('#signupform').submit(function() {
    var errors = 0;
    $("#signupform :input").map(function(){
         if( !$(this).val() ) {
              $(this).parents('td').addClass('warning');
              errors++;
        } else if ($(this).val()) {
              $(this).parents('td').removeClass('warning');
        }   
    });
    if(errors > 0){
        $('#errorwarn').text("All fields are required");
        return false;
    }
    // do the ajax..    
});

The :empty pseudo-selector is used to see if an element contains no childs, you should check the value :

$('#apply-form input').blur(function() {
     if(!this.value) { // zero-length string
            $(this).parents('p').addClass('warning');
     }
});

if ($('input:text').val().length == 0) {
      $(this).parents('p').addClass('warning');
}

Here is an example using keyup for the selected input. It uses a trim as well to make sure that a sequence of just white space characters doesn't trigger a truthy response. This is an example that can be used to begin a search box or something related to that type of functionality.

YourObjNameSpace.yourJqueryInputElement.keyup(function (e){
   if($.trim($(this).val())){
       // trimmed value is truthy meaning real characters are entered
    }else{
       // trimmed value is falsey meaning empty input excluding just whitespace characters
    }
}

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');
}});

Everybody has the right idea, but I like to be a little more explicit and trim the values.

$('#apply-form input').blur(function() {
     if(!$.trim(this.value).length) { // zero-length string AFTER a trim
            $(this).parents('p').addClass('warning');
     }
});

if you dont use .length , then an entry of '0' can get flagged as bad, and an entry of 5 spaces could get marked as ok without the $.trim . Best of Luck.