我正在使用 jQuery 表单验证器插件。该表单有 5 个复选框。其中第一个(主),如果选中,则检查剩余的 4 个并使用户无法更改它们。如果 master 未选中,则其余 4 个框将返回到可由用户切换。此功能工作正常。现在,我想做的是,如果所有复选框都未选中,则使表单无效。我还想要一个特定区域(checkBoxErrorHolder)来存放复选框的验证错误消息。其他错误消息应由其输入显示在其默认位置。这是我到目前为止所拥有的:
<script language="javascript">
$(function() {
$.validator.addMethod("validateCheckBoxes",
function (value, element, params) {
var master=false,
slave1=false,
slave2=false,
slave3=false,
slave4=false;
if ($("#master").attr("checked"))
master = true;
if ($("#slave1").attr("checked"))
slave1 = true;
if ($("#slave2").attr("checked"))
slave2 = true;
if ($("#slave3").attr("checked"))
slave3 = true;
if ($("#slave4").attr("checked"))
slave4 = true;
return (master || (slave1&&slave2&&slave3&&slave4));
},
"One or more check boxes must be checked");
$("#theForm").validate({
rules: {
first: required,
last: required,
email: {required: true, email: true},
master: { required: true,
validateCheckBoxes: true},
errorPlacement: function(error, element) {
$("#checkBoxErrorHolder").html(error);
}
}
slave1: { required: true,
validateCheckBoxes: true},
errorPlacement: function(error, element) {
$("#checkBoxErrorHolder").html(error);
}
}
slave2: { required: true,
validateCheckBoxes: true},
errorPlacement: function(error, element) {
$("#checkBoxErrorHolder").html(error);
}
}
slave3: { required: true,
validateCheckBoxes: true},
errorPlacement: function(error, element) {
$("#checkBoxErrorHolder").html(error);
}
}
slave4: { required: true,
validateCheckBoxes: true,
errorPlacement: function(error, element) {
$("#checkBoxErrorHolder").html(error);
}
}
},
messages: {
first: "required",
last: "required",
email: {
required: "Email address required",
email: "Please supply a valid email address"
}
}
});
});
</script>
<form id="theForm" ...>
<input type="text" name="first" value="" />
<input type="text" name="last" value="" />
<input type="text" name="email" value="" />
<input type="checkbox" id="master" value="master" class="validateCheckBoxes"/>
<input type="checkbox" id="slave1" value="slave1" class="validateCheckBoxes"/>
<input type="checkbox" id="slave2" value="slave2" class="validateCheckBoxes"/>
<input type="checkbox" id="slave3" value="slave3" class="validateCheckBoxes"/>
<input type="checkbox" id="slave4" value="slave4" class="validateCheckBoxes"/>
<input type="submit" />
</form>
<div id="checkBoxErrorHolder"></div>
不用说,我没有得到我预期的结果。