jQuery 复选框验证 - 父复选框和子复选框

jQuery Validation on checkboxes - parent and child checkboxes

我想为复选框编写一个 jQuery 验证规则,其中父复选框类别必须被选中并且该父类别的子类别也必须被选中(如果父复选框有子复选框) .否则表单将不会提交。

下面的代码为第一个父复选框设置了 2 个父复选框类别和 3 个子复选框类别。如果用户选择第一个父复选框 he/she 必须单击子复选框。但是,如果他们单击没有子项的第二个父复选框,则表单可以通过。

 <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。这是故意的。

据我所知 => id 属性在 HTML 中必须是唯一的,我知道这不能解决您的问题,但它是(也许)您可能遇到的另一个问题的提示...

http://www.w3schools.com/tags/att_global_id.asp

最好的 M.

正如其他人所说,id 选择器是唯一的,这意味着当您执行 $('#box_input') 时,您只会获得第一个 object 且 id = 'box_input'。 我建议将 id = 'box_input' 更改为 class = 'box_input'。然后,您可以将 ID 添加到第一个 parent 及其 children。像 id = 'parent_box',对于 children 要么是 id = 'children_1' 等等,要么是 class = 'box_input children'。完成后我会做类似 if ($('#box_input').filter(':checked') && $('.children').filter(':checked')) { return true; }

的事情

你不能使用

var boxes = $('#box_input'); 

因为 id 是唯一的并且

console.log($('#box_input').length)
如果 DOM 中存在元素,

将始终为 1。

...但您可以使用

var boxes = $('input[id=box_input]')

(jQuery 2.1.3 托管于 google)