2016-04-03 48 views
0

亲爱的Javascript专业的,jQuery验证字段名称包含括号的组

我有一个HTML表单,其中包含两组复选框。其中一个组包含复选框,其中应检查通过jQuery验证。另一组不是强制选择。

First group (at least one checkbox should be selected): 
<input type="checkbox" name="appSourceFirstoption[1]" value="Answer 1" id="appSourceFirstoption" /> 
<input type="checkbox" name="appSourceSecondoption[1]" value="Answer 2" id="appSourceSecondoption" /> 
<input type="checkbox" name="appSourceThirdoption[1]" value="Answer 3" id="appSourceThirdoption" /> 


Second group (these checkboxes are voluntary to select): 
<input type="checkbox" name="appSourceVoluntaryFirst[1]" value="Answer 1" id="appSourceVoluntaryFirst" /> 
<input type="checkbox" name="appSourceVoluntarySecond[1]" value="Answer 2" id="appSourceVoluntarySecond" /> 
<input type="checkbox" name="appSourceVoluntaryThird[1]" value="Answer 3" id="appSourceVoluntaryThird" /> 

复选框的名称包含数组符号,例如, checkboxName [1](“1”表示填写表单的人员)。

现在这个完美的作品:

$.validator.addMethod('checkbox', function(value) { 
    return $('input[type=checkbox]:checked').size() > 0; 
    }, 'Please select at least one.'); 

,但它适用于所有的复选框(因此,即使一个复选框,从第二志愿组的验证可以通过)的。

如果我尝试将强制复选框分组,它不起作用。我想这可能是由于他们的名字包含[],如上所述。

// adding the group 
    $.validator.addMethod("checkbox_1", function(value, element) { 
    return $('.checkbox_1:checked').length > 0; 
    }, 'Please select at least one.'); 


    $('#step').validate({ 

    // grouping the checkboxes together 
    groups: { 
    checkbox_1: "appSourceFirstoption[1] appSourceSecondoption[1] appSourceThirdoption[1]" 
    }, 

    // applying the group rules to just one of the checkbox 
    "appSourceFirstoption[1]" : { checkbox_1: true }, 
    } 

你们有什么想法我怎么能解决这个问题?

+0

你能不能请添加你的html代码片段 –

+0

根据请求添加了HTML。 – BigRooster

+0

由于复选框已经是组的一部分,因此给它们所有'name'属性,其中大部分完全没有实际意义。你甚至不需要自定义方法:https://jsfiddle.net/ffk1ubnz/ – Sparky

回答

0

1)你是缺少 “规则” 选项,

rules: { 
     "appSourceFirstoption[1]": { checkbox_1: true } 
     } 

2)改变$('.checkbox_1:checked').length > 0;

$('input[type=checkbox]:checked').length > 0; 

全码

$(document).ready(function() { 


$('#step').validate({ 

    // grouping the checkboxes together 
    groups: { 
       checkbox_1: "appSourceFirstoption[1] appSourceSecondoption[1] appSourceThirdoption[1]" 
      }, 

    // applying the group rules to just one of the checkbox 
    rules: { 
       "appSourceFirstoption[1]": { checkbox_1: true } 
      } 
}); 

$.validator.addMethod("checkbox_1", function (value, element) { 
    return $('input[type=checkbox]:checked').length > 0; 
}, 'Please select at least one.'); 


}); 

工作提琴。 - https://jsfiddle.net/8ukbf3wy/