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

这是我的代码:

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

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

我做错了什么?


当前回答

你可以尝试这样做:

$('#apply-form input[value!=""]').blur(function() {
    $(this).parents('p').addClass('warning');
});

它将只对空值的输入应用.blur()事件。

其他回答

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

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

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

$('#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。修剪。祝你好运。

为什么没有人提到

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

在我看来更像jquery

试试这个:

function empty(){
        if ($('.text').val().length == 0)
        {
            alert("field should not be empty");
        }
    }

一个干净的css解决方案是:

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