使用jQuery选择空文本输入

时间:2021-12-02 08:45:22

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>

9 个解决方案

#1


182  

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);
  });

});

#2


26  

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

#3


19  

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

?

吗?

By the way, your call of:

顺便说一下,你的电话:

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

can be greatly simplified and speeded up with:

可大大简化和加速:

$('#cmdSubmit')...

#4


12  

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 :text portion 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 :text is 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实际上依赖于浏览器在选择器引擎上的构建。当:将文本添加到选择器中时,它将成为一个非标准的CSS选择器,因此必须由Sizzle本身来处理。这意味着Sizzle检查输入的当前值,而不是源HTML中指定的“值”属性。

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.querySelectorAll will only return elements that have value="" in the HTML. Caveat emptor.

因此,这是检查空文本字段的一种聪明的方法,但我认为它依赖于Sizzle引擎特有的行为(即使用输入的当前值而不是在源代码中定义的属性)。Sizzle可以返回与这个选择器文档匹配的元素。querySelectorAll只返回HTML中值为“”的元素。购者自慎。

#5


4  

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

After trying a lots of version I found this the most logical.

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

Note that text is case-sensitive.

注意文本是区分大小写的。

#6


4  

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/

#7


3  

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的第一个答案(带有过滤功能)是最清晰的方法。

#8


2  

I'd recommend:

我建议:

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

#9


0  

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

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

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

#1


182  

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);
  });

});

#2


26  

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

#3


19  

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

?

吗?

By the way, your call of:

顺便说一下,你的电话:

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

can be greatly simplified and speeded up with:

可大大简化和加速:

$('#cmdSubmit')...

#4


12  

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 :text portion 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 :text is 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实际上依赖于浏览器在选择器引擎上的构建。当:将文本添加到选择器中时,它将成为一个非标准的CSS选择器,因此必须由Sizzle本身来处理。这意味着Sizzle检查输入的当前值,而不是源HTML中指定的“值”属性。

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.querySelectorAll will only return elements that have value="" in the HTML. Caveat emptor.

因此,这是检查空文本字段的一种聪明的方法,但我认为它依赖于Sizzle引擎特有的行为(即使用输入的当前值而不是在源代码中定义的属性)。Sizzle可以返回与这个选择器文档匹配的元素。querySelectorAll只返回HTML中值为“”的元素。购者自慎。

#5


4  

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

After trying a lots of version I found this the most logical.

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

Note that text is case-sensitive.

注意文本是区分大小写的。

#6


4  

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/

#7


3  

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的第一个答案(带有过滤功能)是最清晰的方法。

#8


2  

I'd recommend:

我建议:

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

#9


0  

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

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

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