我很难弄清楚这一点。现在我们已经花了 3 个多小时来研究 JQuery 验证的示例和工具。
我想要做的只是要求选中一个复选框和一个单选按钮,但我不在乎需要哪一个。
<form id="form1" action="/controller/action" method="post">
<div class="checkbox"><input type="checkbox" name="box1" class="cBox" /><label for="box1" class="label">Box1</label></div>
<div class="checkbox"><input type="checkbox" name="Box2" class="cBox" /><label for="Box2" class="label">Box2</label></div>
<div class="checkbox"><input type="checkbox" name="Box3" class="cBox" /><label for="Box3" class="label">Box3</label></div>
<div class="radio"><input type="radio" name="print" value="Radio1" class="rad" /><label class="label">Radio1</label></div>
<div class="radio"><input type="radio" name="print" value="Radio2" class="rad" /><label class="label">Radio2</label></div>
<div class="radio"><input type="radio" name="print" value="Radio3" class="rad" /><label class="label">Radio3</label></div>
<input type="submit" value="Submit" />
</form>
任何帮助将不胜感激。
最佳答案
为此,您必须使用 :checked
选择器。虽然 JP 的回答很好,但我可能会这样做:
$('#form1').submit(function() {
if ($('input:checkbox', this).is(':checked') &&
$('input:radio', this).is(':checked')) {
// everything's fine...
} else {
alert('Please select something!');
return false;
}
});
一些注释:
- 我认为使用
is
读起来更好函数,它返回选择器的 bool 值。 - 您可以使用
:radio
和:checkbox
作为选择表单中所有单选按钮和复选框的快捷方式。然而,according to the jQuery manual ,使用这些选择器而不在它们之前指定input
是不好的做法,因为它们的计算结果为*:checkbox
和*:radio
否则,是非常慢的选择器。 - 通过传递
this
作为第二个参数,我们得到 specifying a context用于搜索,因此仅搜索当前表单内的复选框和单选输入。如果没有它,如果页面中碰巧有其他表单,我们可能会得到误报。
关于JQuery 在提交之前需要复选框和单选按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/849155/