使用 jQuery 选择空文本输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1299424/
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 11:09:02  来源:igfitidea点击:

Selecting empty text input using jQuery

jquerycss-selectors

提问by Cros

How do I identify empty textboxes using jQuery? I would like to do it using selectors if it is at all possible. Also, I must select on id since in the real code where I want to use this I don't want to select all text inputs.

如何使用 jQuery 识别空文本框?如果可能的话,我想使用选择器来做到这一点。另外,我必须选择 id ,因为在我想使用它的实际代码中,我不想选择所有文本输入。

In my following two code examples the first one accurately displays the value typed into the textbox "txt2" by the user. The second example identifies that there is an empty textbox, but if you fill it in it still regards it as empty. Why is this?

在我下面的两个代码示例中,第一个示例准确地显示了用户在文本框“txt2”中键入的值。第二个例子识别出有一个空的文本框,但如果你填写它仍然认为它是空的。为什么是这样?

Can this be done using just selectors?

这可以仅使用选择器来完成吗?

This code reports the value in textbox "txt2":

此代码报告文本框“txt2”中的值:

<html>
    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
        <script type="text/javascript">
            $(function() {
                $('#cmdSubmit').click(function() {
                    alert($('[id=txt2]').val());
                });             
            });
        </script>
    </head>
    <body>
        <form>
            <input type="text" name="txt1" id="txt1" value="123" /><br />
            <input type="text" name="txt2" id="txt2" value="" /><br />
            <input type="text" name="txt3" id="txt3" value="abc" /><br />
            <input type="submit" name="cmdSubmit" id='cmdSubmit' value="Send" /><br />
        </form>
    </body>
</html>

This code always reports textbox "txt2" as empty:

此代码始终将文本框“txt2”报告为空:

<html>
    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
        <script type="text/javascript">
            $(function() {
                $('#cmdSubmit').click(function() {
                    if($('[id^=txt][value=""]').length > 0) {
                        if (!confirm("Are you sure you want to submit empty fields?")) {
                            if (event.preventDefault) {
                                event.preventDefault();
                            } else {
                                event.returnValue = false;
                            }
                        }
                    }
                });             
            });
        </script>
    </head>
    <body>
        <form>
            <input type="text" name="txt1" id="txt1" value="123" /><br />
            <input type="text" name="txt2" id="txt2" value="" /><br />
            <input type="text" name="txt3" id="txt3" value="abc" /><br />
            <input type="submit" name="cmdSubmit" id='cmdSubmit' value="Send" /><br />
        </form>
    </body>
</html>

回答by Russ Cam

Another way

其它的办法

$('input:text').filter(function() { return $(this).val() == ""; });

or

或者

$('input:text').filter(function() { return this.value == ""; });

or

或者

// WARNING: if input element does not have the "value" attribute or this attribute was removed from DOM then such selector WILL NOT WORK! 
// For example input with type="file" and file does not selected.
// It's prefer to use "filter()" method.
// Thanks to @AaronLS
$('input:text[value=""]');

Working Demo

工作演示

code from the demo

演示中的代码

jQuery

jQuery

 $(function() {

  $('#button').click(function() {

    var emptyTextBoxes = $('input:text').filter(function() { return this.value == ""; });
    var string = "The blank textbox ids are - \n";

    emptyTextBoxes.each(function() {
      string += "\n" + this.id;
    });
    alert(string);
  });

});

回答by James Wiseman

You could also do it by defining your own selector:

您也可以通过定义自己的选择器来实现:

$.extend($.expr[':'],{
    textboxEmpty: function(el){
        return $(el).val() === "";
    }
});

And then access them like this:

然后像这样访问它们:

alert($(':text:textboxEmpty').length); //alerts the number of text boxes in your selection

回答by cletus

$(":text[value='']").doStuff();

?

?

By the way, your call of:

顺便说一下,你的电话:

$('input[id=cmdSubmit]')...

can be greatlysimplified and speeded up with:

可以通过以下方式大大简化和加速:

$('#cmdSubmit')...

回答by thirdender

As mentioned in the top ranked post, the following works with the Sizzle engine.

如排名靠前的帖子所述,以下内容适用于 Sizzle 引擎。

$('input:text[value=""]');

In the comments, it was noted that removing the :textportion of the selector causes the selector to fail. I believe what's happening is that Sizzle actually relies on the browser's built in selector engine when possible. When :textis added to the selector, it becomes a non-standard CSS selector and thereby must needs be handled by Sizzle itself. This means that Sizzle checks the current value of the INPUT, instead of the "value" attribute specified in the source HTML.

在评论中,注意到删除:text选择器的一部分会导致选择器失败。我相信正在发生的事情是 Sizzle 在可能的情况下实际上依赖于浏览器的内置选择器引擎。当:text添加到选择器时,它成为一个非标准的 CSS 选择器,因此必须由 Sizzle 自己处理。这意味着 Sizzle 检查 INPUT 的当前值,而不是源 HTML 中指定的“value”属性。

So it's a clever way to check for empty text fields, but I think it relies on a behavior specific to the Sizzle engine (that of using the current value of the INPUT instead of the attribute defined in the source code). While Sizzle might return elements that match this selector, document.querySelectorAllwill only return elements that have value=""in the HTML. Caveat emptor.

所以这是一种检查空文本字段的聪明方法,但我认为它依赖于特定于 Sizzle 引擎的行为(使用 INPUT 的当前值而不是源代码中定义的属性)。虽然 Sizzle 可能会返回与此选择器匹配的document.querySelectorAll元素,但只会返回value=""HTML中具有的元素。买者自负。

回答by thirdender

$("input[type=text][value=]")

$("input[type=text][value=]")

After trying a lots of versionI found this the most logical.

尝试了很多版本后,我发现这是最合乎逻辑的。

Note that textis case-sensitive.

请注意,这text是区分大小写的。

回答by Gruffy

Building on @James Wiseman's answer, I am using this:

基于@James Wiseman 的回答,我正在使用这个:

$.extend($.expr[':'],{
    blank: function(el){
        return $(el).val().match(/^\s*$/);
    }
});

This will catch inputs which contain only whitespace in addition to those which are 'truly' empty.

除了那些“真正”空的输入之外,这将捕获仅包含空格的输入。

Example: http://jsfiddle.net/e9btdbyn/

示例:http: //jsfiddle.net/e9btdbyn/

回答by tandrewnichols

There are a lot of answers here suggesting something like [value=""]but I don't think that actually works . . . or at least, the usage is not consistent. I'm trying to do something similar, selecting all inputs with ids beginning with a certain string that also have no entered value. I tried this:

这里有很多答案暗示类似[value=""]但我认为这实际上行不通。. . 或者至少,用法并不一致。我正在尝试做类似的事情,选择所有 id 以某个字符串开头的输入,这些字符串也没有输入值。我试过这个:

$("input[id^='something'][value='']")

but it doesn't work. Nor does reversing them. See this fiddle. The only ways I found to correctly select all inputs with ids beginning with a string and without an entered value were

但它不起作用。也不会逆转它们。看到这个小提琴。我发现正确选择所有 id 以字符串开头且没有输入值的输入的唯一方法是

$("input[id^='something']").not("[value!='']")

and

$("input[id^='something']:not([value!=''])")

but obviously, the double negatives make that really confusing. Probably, Russ Cam's first answer (with a filtering function) is the most clear method.

但显然,双重否定让这真的很令人困惑。可能,Russ Cam 的第一个答案(带有过滤功能)是最清晰的方法。

回答by TM.

I'd recommend:

我建议:

$('input:text:not([value])')

回答by Cros

This will select empty text inputs with an id that starts with "txt":

这将选择带有以“txt”开头的 id 的空文本输入:

$(':text[value=""][id^=txt]')

回答by Tires

Since creating an JQuery object for every comparison is not efficient, just use:

由于为每个比较创建一个 JQuery 对象效率不高,只需使用:

$.expr[":"].blank = function(element) {
    return element.value == "";
};

Then you can do:

然后你可以这样做:

$(":input:blank")