大家好我有jQuery代码来验证是否选中了复选框,如果它们不是警告消息则显示。一切正常。两个不同的复选框组有两条消息。目前,两个消息都显示在最后一个复选框下。我想要的是在"同意"下显示同意消息。复选框并选择" OPTIONS"下的其中一个选项;一组复选框。这是JSFiddle。
这是一段代码:
$(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: 'You must agree before submitting!'
},
},
errorPlacement: function(error, element) {
$('#form_error').append(error);
},
submitHandler: function(form) {
alert('Form Submited');
return false;
}
});
});
$.validator.addMethod('require-one', function(value) {
if ($('#resp01').is(':checked')) {
return $('.require-one:checked').size() > 0;
} else {
return true;
}
}, 'Please select one of the options.');
任何帮助表示感谢。
答案 0 :(得分:1)
你在这里。当您使用errorPlacement
功能时,可以检查element
是否具有特定功能。因为在插入错误消息之前需要知道哪个元素已经过验证。在这种情况下,我使用了元素的类。
$(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: 'You must agree before submitting!'
},
},
errorPlacement: function(error, element) {
if ($(element).hasClass("require-one")) {
$('#require-one-error').append(error);
} else {
$('#resp-error').append(error);
}
},
submitHandler: function(form) {
alert('Form Submited');
return false;
}
});
});
$.validator.addMethod('require-one', function(value) {
if ($('#resp01').is(':checked')) {
return $('.require-one:checked').size() > 0;
} else {
return true;
}
}, 'Please select one of the options.');

* {
font-family: Verdana;
font-size: 96%;
}
label.error {
float: none;
color: red;
margin: 0 .5em 0 0;
vertical-align: top;
font-size: 10px;
display: block
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.js"></script>
<form name="itemForm" id="itemForm" method="post">
<fieldset style="width:200px">
<legend>OPTIONS</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="opt02" 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 require-one-error" id="require-one-error"></div>
<p>
<input name="resp01" type="checkbox" value="Agree" id="resp01" class="resp" />
<label for="resp01">Agree</label>
</p>
<div class="error" id="resp-error"></div>
<input type="submit" />
</form>
&#13;