使用 jQuery 选择空文本输入

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

在下面的两个代码示例中,第一个示例准确地显示用户在文本框“ 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>

此代码总是将文本框“ 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>
114344 次浏览
$(":text[value='']").doStuff();

?

By the way, your call of:

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

can be greatly simplified and speeded up with:

$('#cmdSubmit')...

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

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


});

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

I'd recommend:

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

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

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

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

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

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.

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

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

Note that text is case-sensitive.

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:

$("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

$("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.

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

$.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/

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

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

Then you can do:

$(":input:blank")