jQuery jQuery验证 - 仅在选中单选按钮时,才会检查一组复选框中的至少一个
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19714318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery Validate - at least one from a group of checkboxes is checked only if a radio button is checked
提问by ViaDev
I′m using jquery validate plugin to ensure at least one from a group of three checkboxes is checked and it′s woking fine. But I want validate these checkboxes only if the radio button "Sim" is checked. I don′t know how to do this.
我正在使用 jquery 验证插件来确保一组三个复选框中的至少一个被选中并且它工作正常。但我只想在选中单选按钮“Sim”时验证这些复选框。我不知道该怎么做。
Demo: http://jsfiddle.net/TnmGr
Html Form:
html格式:
<form name="itemForm" id="itemForm" method="post">
<p>
<input name="resp01" type="radio" value="sim" id="resp01-sim" class="resp" /> <label for="resp01-sim">Sim</label>
<input name="resp01" type="radio" value="n?o" id="resp01-nao" class="resp" /> <label for="resp01-nao">N?o</label>
</p>
<fieldset style="width:200px"><legend>Outros catalogos</legend>
<input id="opt01" name="opt01" type="checkbox" value="true" class="require-one" />
<label for="opt01">opt01</label>
<input name="opt01" type="hidden" value="false" /><br />
<input id="opt02" name="opt02" type="checkbox" value="true" class="require-one" />
<label for="opt02">opt02</label>
<input name="river2" type="hidden" value="false" /><br />
<input id="opt03" name="opt03" type="checkbox" value="true" class="require-one" />
<label for="opt03">opt03</label>
<input name="opt03" type="hidden" value="false" /><br />
</fieldset>
<div class="error" id="form_error"></div>
<br />
<input type="submit" />
JS:
JS:
$.validator.addMethod('require-one', function(value) {
return $('.require-one:checked').size() > 0;
}, 'Selecione pelo menos uma das op??es.');
$(document).ready(function(){
var checkboxes = $('.require-one');
var checkbox_names = $.map(checkboxes, function(e, i) {
return $(e).attr("name")
}).join(" ");
$("#itemForm").validate({
groups: {
checks: checkbox_names
},
rules: {
resp01: 'required',
},
messages: {
resp01: { required: 'Selecione uma resposta!' },
},
errorPlacement: function(error, element) {
$('#form_error').append(error);
},
submitHandler: function(form) {
alert('Form Submited');
return false;
}
});
});
回答by Sparky
You simply need to alter the logic of your custom method.
您只需要更改自定义方法的逻辑。
$.validator.addMethod('require-one', function(value) {
if ($('#resp01-sim').is(':checked')) {
return $('.require-one:checked').size() > 0;
} else {
return true;
}
}, 'Selecione pelo menos uma das op??es.');
回答by David Cook
You could try the built-in functionality:
您可以尝试内置功能:
$( "#itemForm" ).validate({
rules: {
opt01: {
required: "#resp01-sim"
}
}
});