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

这是我的代码:

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

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

我做错了什么?


当前回答

如何检查null undefined和空在jquery

  $(document).on('input', '#amt', function(){
    let r1;
    let r2;
    r1 = $("#remittance_amt").val();
    if(r1 === undefined || r1 === null || r1 === '')
    {
      r1 = 0.00;
    }

    console.log(r1);
  });

其他回答

$('#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关键字,如果你只是想引用一个单独的元素(前提是在上下文的后代/子代中有一个文本字段)。

if ($('input:text').val().length == 0) {
      $(this).parents('p').addClass('warning');
}

伟大的答案集合,想补充的是,你也可以这样做,使用:占位符显示的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选择器。如果要对输入使用必需的属性,则可以使用这些选择器。

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

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

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

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