Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

jquery - 使用jQuery检查输入是否为空(Check if inputs are empty using 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.

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

Here is my code:

(这是我的代码:)

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

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

What am I doing wrong?

(我究竟做错了什么?)

  ask by Keith Donegan translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
$('#apply-form input').blur(function()
{
    if( !$(this).val() ) {
          $(this).parents('p').addClass('warning');
    }
});

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:

(并且您不一定需要.length或查看它是否>0因为无论如何空字符串的计算结果为false,但是如果您希望出于可读性目的:)

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

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

(如果您确定它将始终在textfield元素上运行,那么您可以使用this.value 。)

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

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).

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...