jQuery 验证插件:如果单选按钮被选中,则在一组复选框上设置规则

jQuery Validate Plugin: Set rule on a set of checkboxes if radio button is selected

问题:我有两个单选按钮;如果用户选择一个,则会出现一个包含 3 个复选框的列表。必须至少选中这些复选框之一。我如何将其转化为优雅的规则?

html:

<label><input id="optionB_radio" type="radio">Option B</label>
<input id="subOption1_cb" type="checkbox" disabled="disabled">sub option 1</label>  
<input  id="subOption2_cb" type="checkbox" disabled="disabled">sub option 2</label> 
<input id="subOption3_cb" type="checkbox" disabled="disabled">sub option 3</label>  

我目前拥有的是这个......但我希望有一个更优雅的解决方案。

subOption1_cb:
            required:{
                depends: function(el) {
                    return ($("#option1_radio:selected") && $("#subOption2:checked").length == 0 && $("#subOption3:checked").length == 0);
                }
            },
        subOption2_cb:
            required:{
                depends: function(el) {
                    return ($("#option1_radio:selected") && $("#subOption1:checked").length == 0 && $("#subOption3:checked").length == 0);
                }
            },
        subOption3_cb:
            required:{
                depends: function(el) {
                    return ($("#option1_radio:selected") && $("#subOption2:checked").length == 0 && $("#subOption1:checked").length == 0);
                }
            }

你有一堆问题使它无法正常工作...

  • 此插件考虑验证的任何元素必须包含 name 属性,但您有 none。由于所有复选框都是分组的一部分,因此它们可以共享相同的 name。然后通过将 required 规则分配给这个 name,您将自动要求组中至少有一个复选框。

  • 您的对象文字构造不正确。您缺少 opening/closing 大括号 {},它围绕着每个 name.

  • 之后的规则集
  • 您的 "#option1_radio:selected" 选择器与您的单选元素的 id 不匹配。 jQuery .is() 方法中的无线电元素还需要一个 :checked 选择器,而不是 :select.

    $("#optionB_radio").is(":checked")
    
  • 删除 disabled="disabled" 否则这些元素将始终被忽略。

rules 对象:

rules: {
    subOption: { // <- this MUST be the NAME attribute and include braces
        required: {
            depends: function(el) {
                return $("#optionB_radio").is(":checked");
            }
        }
    },
    // other elements
}

HTML:

<label><input id="optionB_radio" type="radio">Option B</label>

<input name="subOption" id="subOption1_cb" type="checkbox">sub option 1</label>  
<input name="subOption" id="subOption2_cb" type="checkbox">sub option 2</label> 
<input name="subOption" id="subOption3_cb" type="checkbox">sub option 3</label>

工作演示:http://jsfiddle.net/fzz7yyL6/