使用 jQuery 检查输入是否为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1854556/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:16:13  来源:igfitidea点击:

Check if inputs are empty using jQuery

jqueryvalidation

提问by Keith Donegan

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?

我究竟做错了什么?

回答by meder omuraliev

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

And you don't necessarily need .lengthor see if it's >0since 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.

如果您确定它总是在文本字段元素上运行,那么您可以使用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 thiskeyword if you just want a reference to a lone element (provided there's one textfield in the context's descendants/children).

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

回答by Alex Sexton

Everybody has the right idea, but I like to be a little more explicit and trim the values.

每个人都有正确的想法,但我喜欢更明确一点并调整价值观。

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

if you dont use .length , then an entry of '0' can get flagged as bad, and an entry of 5 spaces could get marked as ok without the $.trim . Best of Luck.

如果您不使用 .length ,则 '0' 条目可能会被标记为错误,并且 5 个空格的条目可能会在没有 $.trim 的情况下被标记为 ok 。祝你好运。

回答by drewdeal

Doing it on blur is too limited. It assumes there was focus on the form field, so I prefer to do it on submit, and map through the input. After years of dealing with fancy blur, focus, etc. tricks, keeping things simpler will yield more usability where it counts.

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

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

回答by Graviton

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

回答by Zigri2612

you can use also..

你也可以用..

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

if you have doubt about spaces,then try..

如果您对空格有疑问,请尝试..

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

回答by Jamie Pate

how come nobody mentioned

怎么没人提

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

seems more jquery-like to me

对我来说似乎更像 jquery

回答by Ouss Ama

The keyup event will detect if the user has cleared the box as well (i.e. backspace raises the event but backspace does not raise the keypress event in IE)

keyup 事件将检测用户是否也清除了该框(即退格会引发事件,但退格不会引发 IE 中的按键事件)

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

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

回答by Dave Ward

Consider using the jQuery validation plugininstead. It may be slightly overkill for simple required fields, but it mature enough that it handles edge cases you haven't even thought of yet (nor would any of us until we ran into them).

考虑改用jQuery 验证插件。对于简单的必填字段,它可能有点矫枉过正,但它足够成熟,可以处理您甚至还没有想到的边缘情况(在我们遇到它们之前,我们中的任何人都不会)。

You can tag the required fields with a class of "required", run a $('form').validate() in $(document).ready() and that's all it takes.

您可以使用“必需”类标记必填字段,在 $(document).ready() 中运行 $('form').validate() 就可以了。

It's even hosted on the Microsoft CDN too, for speedy delivery: http://www.asp.net/ajaxlibrary/CDN.ashx

它甚至也托管在 Microsoft CDN 上,以便快速交付:http: //www.asp.net/ajaxlibrary/CDN.ashx

回答by CMS

The :emptypseudo-selector is used to see if an element contains no childs, you should check the value :

:empty伪选择用于查看元素是否包含没有孩子的,你应该检查该值:

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

回答by xorinzor

There is one other thing you might want to think about, Currently it can only add the warning class if it is empty, how about removing the class again when the form is not empty anymore.

您可能还需要考虑另一件事,目前它只能在为空时添加警告类,当表单不再为空时再次删除该类如何。

like this:

像这样:

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