在 jquery 中检查至少一个复选框验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13097747/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
check at least one checkbox validation in jquery
提问by Ravneet 'Abid'
I have some checkboxes, something like this:
我有一些复选框,如下所示:
<form name="submit-form" name="submit-form">
<label>property1</label>
<input type="checkbox" name="property1"><br>
<label>property2</label>
<input type="checkbox" name="property2"><br>
<label>property3</label>
<input type="checkbox" name="property3"><br>
<label>property4</label>
<input type="checkbox" name="property4"><br>
<label>property5</label>
<input type="checkbox" name="property5"><br>
<label>property6</label>
<input type="checkbox" name="property6"><br>
<input type="submit">
</form>
I would like to validate that atleast one checkbox at a time. plz help me. thanks in advance
我想一次验证至少一个复选框。请帮助我。提前致谢
回答by rahul
$("#YourbuttonId").click(function(){
if($('#YourTableId').find('input[type=checkbox]:checked').length == 0)
{
alert('Please select atleast one checkbox');
}
});
Update:
更新:
i saw your code and seems like you are using jquery validation plugin in that case this post will help you
我看到了你的代码,似乎你正在使用 jquery 验证插件,在这种情况下,这篇文章会对你有所帮助
and try giving your checkbox same name which exist in a group
并尝试为组中存在的复选框提供相同的名称
http://forum.jquery.com/topic/check-that-at-least-1-checkbox-is-checked-using-jquery-validate-plugin
http://forum.jquery.com/topic/check-that-at-least-1-checkbox-is-checked-using-jquery-validate-plugin
回答by DA.
I'd wrap them all in a container with a div just for easier selecting, and then you can use:
我将它们全部包装在一个带有 div 的容器中,以便于选择,然后您可以使用:
if($('#wrapperID input:checked').length > 0) {
'at least one is checked
}
回答by Pragnesh Chauhan
try this
尝试这个
$('form').submit(function(e) {
if($("input:checked").length == 0){
alert('please checked atleast one');
}
});?
回答by Tats_innit
See this demo: http://jsfiddle.net/RGUTv/ORyour specific case demo here: http://jsfiddle.net/J98Ua/
请参阅此演示:http: //jsfiddle.net/RGUTv/或您的具体案例演示:http: //jsfiddle.net/J98Ua/
My old response here: validation for at least one checkbox
我在这里的旧回复:验证至少一个复选框
hope rest fits the needs! :)
希望休息能满足需要! :)
code
代码
$(document).ready(function() {
$('#my-form').submit(function() {
amIChecked = false;
$('input[type="checkbox"]').each(function() {
if (this.checked) {
amIChecked = true;
}
});
if (amIChecked) {
alert('atleast one box is checked');
}
else {
alert('please check one checkbox!');
}
return false;
});
});?