Check if inputs are empty using jQuery



7 Answers

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.

Question

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?




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.




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>




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



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



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



$(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




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



Related