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:10

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
    }
}
查看更多
一个人的天荒地老
3楼-- · 2018-12-31 09:11

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

查看更多
余生请多指教
4楼-- · 2018-12-31 09:13

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');
}});
查看更多
弹指情弦暗扣
5楼-- · 2018-12-31 09:13
<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>// :)
查看更多
宁负流年不负卿
6楼-- · 2018-12-31 09:17

how come nobody mentioned

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

seems more jquery-like to me

查看更多
人间绝色
7楼-- · 2018-12-31 09:21

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');
    }
});
查看更多
登录 后发表回答