我正在使用jquery validate插件来确保选中一组三个复选框中的至少一个,这样就可以了。但是我只想在选中单选按钮“Sim”时验证这些复选框。我不知道该怎么做。
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;
}
});
});
答案 0 :(得分:9)
您只需要改变自定义方法的逻辑。
$.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.');
答案 1 :(得分:-1)
您可以尝试内置功能:
$( "#itemForm" ).validate({
rules: {
opt01: {
required: "#resp01-sim"
}
}
});