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

这是我的代码:

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

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

我做错了什么?


当前回答

为什么没有人提到

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

在我看来更像jquery

其他回答

伟大的答案集合,想补充的是,你也可以这样做,使用:占位符显示的CSS选择器。使用IMO会更简洁一些,特别是如果您已经在使用jQ并且在输入中有占位符。

如果($('输入# cust-descrip ') . (': placeholder-shown ')) { console.log(“空”); } $('输入# cust-descrip”)。On ('blur', ",函数(ev) { 如果(! $('输入# cust-descrip ') . (': placeholder-shown ')) { console.log(“文本!”); } 其他{ console.log(“空!”); } }); < script src = " https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js " > < /脚本> <input type="text" class="form-control" id=" cast - Description" autocomplete="off" placeholder="Description">

如果需要输入,还可以使用:valid和:invalid选择器。如果要对输入使用必需的属性,则可以使用这些选择器。

<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>// :)

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

是这样的:

$('#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[value!=""]').blur(function() {
    $(this).parents('p').addClass('warning');
});

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

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

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