Check if inputs are empty using jQuery

2018-12-31 08:40发布

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?

16条回答
十年一品温如言
2楼-- · 2018-12-31 09:24

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.

查看更多
千与千寻千般痛.
3楼-- · 2018-12-31 09:26

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');
    }
});
查看更多
只若初见
4楼-- · 2018-12-31 09:27
$(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

查看更多
何处买醉
5楼-- · 2018-12-31 09:29

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>

查看更多
登录 后发表回答