【发布时间】:2015-06-08 19:27:09
【问题描述】:
我想为复选框编写一个 jQuery 验证规则,其中必须选择父复选框类别并且也必须选择该父复选框的子类别(如果父复选框有子复选框)。否则表单将不会提交。
下面的代码有 2 个父复选框类别和第一个父复选框的 3 个子复选框类别。如果用户选择第一个父复选框,他/她必须单击一个子复选框。但是,如果他们单击没有子项的第二个父复选框,则表单可以通过。
<ul id = "checklist">
<li id = "box">
<label> <input id = "box_input" type = "checkbox"> "A CheckBox"</label>
<ul id = "checklist_children">
<li id = "box">
<label> <input id = "box_input" type = "checkbox"> "A CheckBox"</label>
</li>
<li id = "box">
<label> <input id = "box_input" type = "checkbox"> "A CheckBox"</label>
</li>
<li id = "box">
<label> <input id = "box_input" type = "checkbox"> "A CheckBox"</label>
</li>
</ul>
</li>
<li id = "box">
<label> <input id = "box_input" type = "checkbox"> "A CheckBox"</label>
</li>
</ul>
关于验证到目前为止,我写的是一个方法,它查看是否选择了任何框,如果是,则不需要验证。我要修改这个
...
my_checkbox_rule: {
required: function (element) {
var boxes = $('#box_input');
if (boxes.filter(':checked').length == 0) {
return true;
}
},
minlength: 1
},
...
我想修改上面的代码以允许该功能。我可以提供比需要更多的信息。
作为额外说明,子框与父框具有相同的 id。这是故意的。
【问题讨论】:
-
您的
input元素必须包含name属性,否则 jQuery Validate 插件将不起作用。 -
就像其他人告诉你的那样,你的
id必须是唯一的,否则你会遇到无效的 HTML 和 JavaScript 的其他问题。
标签: jquery checkbox jquery-validate