我在HTML中有几个复选框,我想确保至少检查一个。我想使用jQuery验证器,以便我不需要管理错误消息演示业务。另外,我想在提交表单之前这样做。我想通过单击按钮来验证它。我的代码喜欢这个:
HTML:
<div class="control-group">
<label class="label-class">
<input type="checkbox" data-validation-minchecked-minchecked="1" value="1" name="testing"></input>
</label>
<label class="label-class">
<input type="checkbox" data-validation-minchecked-minchecked="1" value="1" name="testing"></input>
</label>
<label class="label-class">
<input type="checkbox" data-validation-minchecked-minchecked="1" value="1" name="testing"></input>
</label>
</div>
JavaScript的:
$("button").click(function(e) {
var isOk = true;
isOk = $("myForm").validate({
rules: {
testing: {
minlength: 1
}
},
message: {
testing: "please select at least one item"
}
});
return isOk;
});
但这不行。我该如何实现这个逻辑?
答案 0 :(得分:1)
尝试使用------&#34;必需:true&#34;
答案 1 :(得分:1)
如果复选框元素超过1,则提交表单。
HTML:
<div class="control-group">
<label class="label-class">
<input type="checkbox" data-validation-minchecked-minchecked="1" value="1" name="testing"></input>
</label>
<label class="label-class">
<input type="checkbox" data-validation-minchecked-minchecked="1" value="1" name="testing"></input>
</label>
<label class="label-class">
<input type="checkbox" data-validation-minchecked-minchecked="1" value="1" name="testing"></input>
</label>
</div>
<button id="button">Submit</button>
JQuery的:
$("#button").click(function(e) {
return ($(":checked").length > 0);
});
或者:
$("#button").click(function(e) {
if ($(":checked").length > 0)
// Submit your form here
else
// Display warning here
});
答案 2 :(得分:0)
你的代码中有很多错误。 我已经更改了代码,更改了复选框的名称,为它们添加了类以及其他内容。
<form id="myForm"><div class="control-group">
<label class="label-class">
<input type="checkbox" class="group1" value="1" name="testing1"></input>
</label>
<label class="label-class">
<input type="checkbox" class="group1" value="1" name="testing2"></input>
</label>
<label class="label-class">
<input type="checkbox" class="group1" value="1" name="testing3"></input>
</label>
<button>Button</button>
</div>
</form>
和javascript:
$("#myForm").validate({
rules: {
testing1: {
require_from_group: [1, ".group1"]
},
testing2: {
require_from_group: [1, ".group1"]
},
testing3: {
require_from_group: [1, ".group1"]
}
},
message: {
testing1: "please select at least one item",
testing2: "please select at least one item",
testing3: "please select at least one item",
}
});
$("button").click(function(e) {
return $("#myForm").valid();
});
请参阅jsFiddle