jQuery Validate-仅在选中单选按钮的情况下,才选中一组复选框中的至少一个 [英] jQuery Validate - at least one from a group of checkboxes is checked only if a radio button is checked
本文介绍了jQuery Validate-仅在选中单选按钮的情况下,才选中一组复选框中的至少一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用jquery validate插件来确保选中三个复选框中的至少一个,并且可以正常工作.但是,仅在选中单选按钮"Sim"时,我才想验证这些复选框.我不知道该怎么做.
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.
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 :
$.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;
}
});
});
推荐答案
您只需要更改自定义方法的逻辑即可.
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.');
演示: http://jsfiddle.net/TnmGr/4/
DEMO: http://jsfiddle.net/TnmGr/4/
这篇关于jQuery Validate-仅在选中单选按钮的情况下,才选中一组复选框中的至少一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文