如何使用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>
Run Code Online (Sandbox Code Playgroud)
此代码始终将文本框"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?")) { …Run Code Online (Sandbox Code Playgroud) 令我感到惊讶的是,Sizzle(jQuery使用的选择器引擎)带有内置:nth-child()选择器,但缺少:nth-of-type()选择器.
为了说明和之间的区别:nth-child()并:nth-of-type()说明问题,请考虑以下HTML文档:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>:nth-of-type() in Sizzle/jQuery?</title>
<style>
body p:nth-of-type(2n) { background: red; }
</style>
</head>
<body>
<p>The following CSS is applied to this document:</p>
<pre>body p:nth-of-type(2n) { background: red; }</pre>
<p>This is paragraph #1.</p>
<p>This is paragraph #2. (Should be matched.)</p>
<p>This is paragraph #3.</p>
<p>This is paragraph #4. (Should be matched.)</p>
<div>This is not a paragraph, but a <code>div</code>.</div>
<p>This is paragraph …Run Code Online (Sandbox Code Playgroud)