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

时间:2015-06-08 19:27:10

标签: jquery checkbox jquery-validate

我想为复选框编写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。这是有意的。

3 个答案:

答案 0 :(得分:0)

据我所知=&gt; id属性必须在HTML中是唯一的,我知道这不能解决你的问题,但它暗示了(也许)你可能得到的另一个问题...

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

Best M。

答案 1 :(得分:0)

正如其他人所说的那样,id选择器是唯一的,这意味着当你执行$('#box_input')时,你只能获得id ='box_input'的第一个对象。 我建议更改id = 'box_input' class = 'box_input'。然后,您可以将ID添加到第一个父级及其子级。类似id = 'parent_box'的内容,以及id = 'children_1'等儿童或class = 'box_input children'。如果完成,我会做 if ($('#box_input').filter(':checked') && $('.children').filter(':checked')) { return true; }

之类的事情

答案 2 :(得分:0)

你不能使用

var boxes = $('#box_input'); 

因为id是唯一的

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

将始终为1。

...但你可以使用

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

(jQuery 2.1.3托管在谷歌上)

相关问题