使用 jQuery 检查输入是否为空 [英] Check if inputs are empty using jQuery

查看:27
本文介绍了使用 jQuery 检查输入是否为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单,我希望填写所有字段.如果单击某个字段然后未填写,我希望显示红色背景.

I have a form that I would like all fields to be filled in. If a field is clicked into and then not filled out, I would like to display a red background.

这是我的代码:

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

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

It applies the warning class regardless of the field being filled in or not.

我做错了什么?

推荐答案

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

并且您不一定需要 .length 或查看它是否为 >0 因为空字符串无论如何都会评估为 false 但如果您想提高可读性目的:

And you don't necessarily need .length or see if it's >0 since an empty string evaluates to false anyway but if you'd like to for readability purposes:

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

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

If you're sure it will always operate on a textfield element then you can just use this.value.

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

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

Also you should take note that $('input:text') grabs multiple elements, specify a context or use the this keyword if you just want a reference to a lone element (provided there's one textfield in the context's descendants/children).

这篇关于使用 jQuery 检查输入是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆