jQuery Validation 至少选中了一个复选框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20159867/
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
jQuery Validation at least one checkbox is selected
提问by Hello Universe
I have the following piece of html code for form checkboxes
我有以下表单复选框的 html 代码
<div class="drinking col-xs-12">
<div class="col-xs-7 drinkingLeft">
<input type="checkbox" name="allwines" id="allwines" value="0" class="require-one col-xs-1 styled myClassA" value="0" data-label="All Wines" />
<input id='allwinesHidden' type='hidden' value='0' name='allwines'>
</div>
<div class="col-xs-5 drinkingLeft">
<input type="checkbox" name="beer" id="beer" value="0" class="require-one col-xs-1 styled myClassB" value="0" data-label="Beer" />
<input id='beerHidden' type='hidden' value='0' name='beer'>
</div>
<div class="clearix"></div>
<div class="col-xs-7 drinkingLeft">
<input type="checkbox" name="redwines" id="redwines" value="0" class="require-one col-xs-1 styled myClassC" value="0" data-label="Red Wines" />
<input id='redwinesHidden' type='hidden' value='0' name='redwines'>
</div>
<div class="col-xs-5 drinkingLeft">
<input type="checkbox" name="cider" id="cider" value="0" class="require-one col-xs-1 styled myClassD" value="0" data-label="Cider" />
<input id='ciderHidden' type='hidden' value='0' name='cider'>
</div>
<div class="clearix"></div>
<div class="col-xs-7 drinkingLeft">
<input type="checkbox" name="whitewines" id="whitewines" value="0" class="require-one col-xs-1 styled myClassE" value="0" data-label="White Wines" />
<input id='whitewinesHidden' type='hidden' value='0' name='whitewines'>
</div>
<div class="col-xs-5 drinkingLeft">
<input type="checkbox" name="spirits" id="spirits" value="0" class="require-one col-xs-1 styled myClassF" value="0" data-label="Spirits" />
<input id='spiritsHidden' type='hidden' value='0' name='spirits'>
</div>
<div class="clearix"></div>
<div class="col-xs-7 drinkingLeft">
<input type="checkbox" name="sparkling" id="sparkling" value="0" class="require-one col-xs-1 styled myClassG" value="0" data-label="Sparkling/Champagne" />
<input id='sparklingHidden' type='hidden' value='0' name='sparkling'>
</div>
<div class="col-xs-5 drinkingLeft">
<input type="checkbox" name="fortified" id="fortified" value="0" class="require-one col-xs-1 styled myClassH" value="0" data-label="Fortified" />
<input id='fortifiedHidden' type='hidden' value='0' name='fortified'>
</div>
<div id="error_msg3"></div>
<div class="clearix"></div>
</div>
</div>
I want to make sure that at least one of the check boxes is selected.
我想确保至少选中了一个复选框。
I want that NOTas an alert box ; however the message need to show up in the div error-msg3.
我希望它不是一个警告框;但是消息需要显示在 div error-msg3 中。
Please note that all the inputs have different class names and ids. A staging link is at
请注意,所有输入都有不同的类名和 ID。暂存链接位于
I am using jQuery validation to validate rest of the form. Will be nice to get solution through jquery validation.
我正在使用 jQuery 验证来验证表单的其余部分。通过 jquery 验证获得解决方案会很好。
Thanks in advance
提前致谢
回答by Paul TopRank
This is very simple......
这个很简单......
function validate_form()
{
valid = true;
if($('input[type=checkbox]:checked').length == 0)
{
alert ( "ERROR! Please select at least one checkbox" );
valid = false;
}
return valid;
}
HTML
HTML
<form name="myform" method="post" action="#" onsubmit="return validate_form();">
<input type="checkbox" name="box1" value="box1">Box1
<input type="checkbox" name="box2" value="box2">Box2
<input name="submit" type="submit" value="Submit"/>
</form>
回答by Balthazar
You will have to change the name attributes of the checkboxes, and add a rule for it with the minlength
set to 1.
您必须更改复选框的名称属性,并为其添加minlength
设置为 1的规则。
You can after show the custom message and append it to #error_msg3
with :
您可以在显示自定义消息后将其附加到#error_msg3
:
if(element.attr("name") == "check") error.appendTo("#error_msg3")
EDIT
编辑
$("input[type='checkbox'][name='check']").change(function() {
if ($("input[type='checkbox'][name='check']:checked").length){
$(this).valid()
}
})
EDIT 2
编辑 2
I've updated the Fiddle, now the message toggles correctly when you have at least one checkbox checked or not.
我已经更新了 Fiddle,现在当您至少选中一个复选框时,消息会正确切换。
$("input[type='checkbox'][name='check']").change(function() {
$('#submitDetails').valid();
});
回答by Sparky
Quote OP:
报价:
"I want to make sure that at least one of the check boxes is selected."
“我想确保至少选中了一个复选框。”
If you want to use the jQuery Validate plugin, and all checkboxes have a different name
, simply use the require_from_group
method that's part of the additional-methods.js
file.
如果您想使用 jQuery Validate 插件,并且所有复选框都有不同的name
,只需使用作为文件require_from_group
一部分的方法。additional-methods.js
Since you already have a common class on these checkboxes called require-one
, it's even easier.
由于您在这些复选框上已经有一个名为 的公共类require-one
,因此它更容易。
$('#form').validate({
rules: {
fieldname: {
require_from_group: [1, '.require-one']
},
// declare same rule on all eight checkboxes
....
....
}
});
However, rather than declare all eight of these within .validate()
, you can use the .rules('add')
method inside of a jQuery .each()
to declare them all at once.
但是,.validate()
您可以使用.rules('add')
jQuery 内部的方法.each()
一次性声明所有这八个,而不是在 中声明所有这八个。
$('.require-one').each(function () {
$(this).rules('add', {
require_from_group: [1, this],
messages: {
require_from_group: "please check one"
}
});
});
Then to combine all eight messages into one, use the groups
option...
然后要将所有八条消息合二为一,请使用groups
选项...
$('#form').validate({
groups: { // combine these error messages into one
checkboxes: 'allwines beer redwines cider whitewines spirits sparkling fortified'
}
});
Working DEMO: http://jsfiddle.net/JVWu2/1/
工作演示:http: //jsfiddle.net/JVWu2/1/
Placing your error message into the #error_msg3
error box is no different than placing any of your other jQuery Validate messages.
将错误消息放入#error_msg3
错误框中与将任何其他 jQuery 验证消息放入没有什么不同。
回答by Sridhar R
Try with this
试试这个
$("#YourbuttonId").click(function(){
if($('input[type=checkbox]:checked').length == 0)
{
alert('Please select atleast one checkbox');
}
});
By Plugin
通过插件
HTML
HTML
<label class="checkbox inline">
<input type="checkbox" id="typecb1" name="spamm[]" value="Loading Point"> Loading Point
</label>
<label class="checkbox inline">
<input type="checkbox" id="typecb2" name="spamm[]" value="Unloading Point"> Unloading Point
</label>
<label class="checkbox">
<input type="checkbox" id="typecb3" name="spamm[]" value="Retailer Unloading"> Retailer Unloading
</label>
Script
脚本
rules:{
"spamm[]": {
required: true,
minlength: 1
}
}
回答by Tushar Gupta - curioustushar
Try
尝试
adding this code will do
添加此代码会做
var chck = $('input[type=checkbox]');
chck.addClass('check-one');
$.validator.addMethod('check-one', function (value) {
return (chck.filter(':checked').length > 0);
}, 'Check at least one checkbox');
fiddle Demofiddle Demo
Group will show error in front first check-box only
组将仅在前面的第一个复选框中显示错误
var chck = $('input[type=checkbox]');
chck.addClass('check-one');
$.validator.addMethod('check-one', function (value) {
return (chck.filter(':checked').length > 0);
}, 'Check at least one checkbox');
var chk_names = $.map(chck, function (el, i) {
return $(el).prop("name");
}).join(" ");
$("#submitDetails").validate({
groups: {
checks: chk_names
},
submitHandler: function (form) {
alert('Form Submited');
return false;
}
});
如果您希望错误显示在所有复选框前,请删除组
$("#submitDetails").validate({
submitHandler: function (form) {
alert('Form Submited');
return false;
}
});