我尝试使用自定义验证功能来检查是否至少选中了一个复选框。但是验证功能没有触发。我错过了什么?
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script type="text/javascript" src="../Scripts/jquery-1.8.0.js"></script>
<script type="text/javascript" src="../Scripts/jquery.validate.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.validator.addMethod("fruits", function(value, elem, params) {
if($(".fruits:checkbox:checked").length > 0){
return true;
}else {
return false;
}
},"pick at least one plz");
$("#form1").validate({
rules:{
fruits:{
fruits: true
}
},
submitHandler: function(form) {
alert("submitting...");
form.submit();
},
invalidHandler: function(form){
alert("invalid form");
}
});
});
</script>
</head>
<body>
<form id="form1">
<input type="checkbox" class="{fruits: true}" name="fruits" id="chkApple" value="1" />Apple<br />
<input type="checkbox" class="fruits: true}" name="fruits" id="chkBanana" value="2" />Banana<br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
答案 0 :(得分:0)
尝试:
$.validator.addMethod("fruits", function(value, elem, params) {
return $(".fruits").is(":checked")
},"pick at least one plz");
答案 1 :(得分:0)
用这个
替换你的代码if($(".fruits").is(":checked")){
答案 2 :(得分:0)
答案 3 :(得分:0)
点击此链接source
$(document).ready(function(){
$('#submit_button').click(function() {
if (!$("input[@name='name']:checked").val()) {
alert('Nothing is checked!');
return false;
}
else {
alert('One of the buttons is checked!');
}
});
});
答案 4 :(得分:0)
我得到了它的工作。没有触发的问题是由有问题的编码问题引起的。解决之后,调用自定义函数。但$(".fruits").is(":checked
语法对我有用,它一直说没有选择。所以我带着for
循环上学了。
<html>
<head>
<title></title>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$.validator.addMethod("fruits", function (value, elem, params) {
var items = $("input[name^='fruits']");
for (i = 0; i < items.length; i++) {
if ($(items[i]).is(":checked")) {
return true;
}
}
return false;
}, "pick one plz");
$("#form1").validate({
rules: {
fruits: {
fruits: true
}
},
submitHandler: function (form) {
alert("submitting...");
form.submit();
},
invalidHandler: function (form) {
alert("invalid form");
}
});
});
</script>
</head>
<form id="form1">
<input type="checkbox" class="{fruits: true}" name="fruits" id="chkApple" value="1" />Apple<br />
<input type="checkbox" class="fruits: true}" name="fruits" id="chkBanana" value="2" />Banana<br />
<input type="submit" value="Submit" />
</form>
<body>
</body>
</html>