本文介绍了提交前的jQuery Require复选框和单选按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我很难解决这个问题.过去3个小时以来,我们一直在研究用于JQuery验证的示例和工具.
I am having one heck of a hard time trying to figure this out. Been looking at examples and tools for JQuery validation for over 3 hours now.
我想做的就是要求选中一个复选框和一个单选按钮,但是我不在乎哪个是必需的.
All I want to do is require that a checkbox is selected and a radio button, but I don't care which one is required.
<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的回答很好,但我可能会这样做:
To do this you have to use the :checked
selector. Although JP's answer is fine, I'd probably do this:
$('#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
函数会更好,该函数返回选择器的布尔值 - 您可以使用
:radio
和:checkbox
作为选择表单中所有单选和复选框的快捷方式.但是,根据jQuery手册,在不指定input
的情况下使用这些选择器是一种不好的做法在它们之前,因为它们的值为*:checkbox
和*:radio
,否则它们是非常慢的选择器. - 通过传递
this
作为第二个参数,我们指定上下文搜索,因此仅搜索当前表单内的复选框和单选输入.没有它,如果页面中碰巧还有另一种形式,我们可能会得到误报.
- I think it reads better to use the
is
function, which returns a boolean of the selector. - You can use
:radio
and:checkbox
as a shortcut for selecting all radios and checkboxes in a form. However, according to the jQuery manual, it is bad practice to use these selectors without specifyinginput
before them, as they evaluate to*:checkbox
and*:radio
otherwise, which are very slow selectors. - By passing
this
as the second argument we are specifying a context for the search, and thus are only searching for checkboxes and radio inputs inside the current form. Without it we might get false positives if there happens to be another form in the page.
这篇关于提交前的jQuery Require复选框和单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!