如何验证具有多个复选框的表单以至少选中一个 [英] How to validate a form with multiple checkboxes to have atleast one checked
问题描述
我正在尝试使用 jquery 的验证插件来验证表单.我想要求用户在一个组中至少选中一个复选框,以便提交表单.这是我的 jquery 代码:
I'm trying to validate a form using the validate plugin for jquery. I want to require that the user check at least one checkbox in a group in order for the form to be submitted. Here's my jquery code:
$().ready(function() {
$("#subscribeForm").validate({
rules: { list: {required: "#list0:checked"} },
messages: { list: "Please select at least one newsletter"}
});
});
这里是 html 表单:
and here's the html form:
<form action="" method="GET" id="subscribeForm">
<fieldset id="cbgroup">
<div><input name="list" id="list0" type="checkbox" value="newsletter0" >zero</div>
<div><input name="list" id="list1" type="checkbox" value="newsletter1" >one</div>
<div><input name="list" id="list2" type="checkbox" value="newsletter2" >two</div>
</fieldset>
<input name="submit" type="submit" value="submit">
问题是即使没有检查任何内容,表单也会提交.我该如何解决?
The problem is that the form submits even if nothing is checked. How can I resolve this?
推荐答案
下面的这个脚本或许应该让你走上正轨?
This script below should put you on the right track perhaps?
您可以保持此 html 不变(尽管我将方法更改为 POST):
You can keep this html the same (though I changed the method to POST):
<form method="POST" id="subscribeForm">
<fieldset id="cbgroup">
<div><input name="list" id="list0" type="checkbox" value="newsletter0" >zero</div>
<div><input name="list" id="list1" type="checkbox" value="newsletter1" >one</div>
<div><input name="list" id="list2" type="checkbox" value="newsletter2" >two</div>
</fieldset>
<input name="submit" type="submit" value="submit">
</form>
这个 javascript 验证
and this javascript validates
function onSubmit()
{
var fields = $("input[name='list']").serializeArray();
if (fields.length === 0)
{
alert('nothing selected');
// cancel submit
return false;
}
else
{
alert(fields.length + " items selected");
}
}
// register event on form, not submit button
$('#subscribeForm').submit(onSubmit)
您可以在此处找到工作示例
更新(2012 年 10 月)
另外应该注意的是复选框必须有一个名称"属性,否则它们将不会被添加到数组中.只有id"是行不通的.
UPDATE (Oct 2012)
Additionally it should be noted that the checkboxes must have a "name" property, or else they will not be added to the array. Only having "id" will not work.
更新(2013 年 5 月)
将提交注册移至 javascript 并将提交注册到表单上(本来应该如此)
UPDATE (May 2013)
Moved the submit registration to javascript and registered the submit onto the form (as it should have been originally)
更新(2016 年 6 月)
将 == 更改为 ===
UPDATE (June 2016)
Changes == to ===
这篇关于如何验证具有多个复选框的表单以至少选中一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!