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

这是我的代码:

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

其他回答

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

keyup事件也会检测用户是否清除了方框(例如backspace会引发事件,但在IE中backspace不会引发按键事件)

    $("#inputname").keyup(function() {

if (!this.value) {
    alert('The box is empty');
}});

请使用此代码输入文本

$('#search').on("input",function (e) {

});

你可以尝试这样做:

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

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

if($("#textField").val()!=null)

这对我很有用