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

这是我的代码:

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

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

我做错了什么?


当前回答

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

是这样的:

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

其他回答

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

你不一定需要。length,或者看看它是否为>0,因为空字符串的值无论如何都是假的,但如果你为了可读性考虑:

$('#apply-form input').blur(function()
{
    if( $(this).val().length === 0 ) {
        $(this).parents('p').addClass('warning');
    }
});

如果你确定它总是操作文本字段元素,那么你可以使用this.value。

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

此外,你应该注意$('input:text')抓取多个元素,指定一个上下文或使用this关键字,如果你只是想引用一个单独的元素(前提是在上下文的后代/子代中有一个文本字段)。

为什么没有人提到

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

在我看来更像jquery

:empty伪选择器用于检查元素是否不包含子元素,你应该检查它的值:

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

可以考虑使用jQuery验证插件。对于简单的必填项,它可能有点过分,但它足够成熟,可以处理您甚至还没有想到的边缘情况(我们在遇到它们之前也不会想到)。

你可以用类"required"来标记必填字段,在$(document).ready()中运行$('form').validate(),这就是它所需要的。

它甚至也托管在微软CDN上,以便快速交付:http://www.asp.net/ajaxlibrary/CDN.ashx

你可以用also..

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

如果你对空格有疑问,那么试试..

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