我有一个表格,我希望所有的字段都被填写。如果单击一个字段,然后没有填写,我想显示一个红色背景。

这是我的代码:

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

无论字段是否填写,它都应用警告类。

我做错了什么?


当前回答

每个人都有正确的想法,但我喜欢更明确一点,并精简价值观。

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

如果你不使用.length,那么一个'0'的条目会被标记为坏的,一个5个空格的条目可以被标记为没有$的ok。修剪。祝你好运。

其他回答

还有一件事你可能想要考虑,目前它只能添加警告类如果它是空的,如何删除类再次当表单不再为空。

是这样的:

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

在模糊上做太有限了。它假设表单字段是重点,所以我更喜欢在提交时执行,并通过输入进行映射。在处理了多年花哨的模糊、聚焦等技巧后,让事情变得更简单会在重要的地方产生更多的可用性。

$('#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..    
});

下面是一个使用keyup选择输入的例子。它还使用修剪来确保空白字符序列不会触发真值响应。这是一个可以用来开始搜索框或与这类功能相关的东西的示例。

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
    }
}
if ($('input:text').val().length == 0) {
      $(this).parents('p').addClass('warning');
}

为什么没有人提到

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

在我看来更像jquery