如何验证具有多个复选框的表单以至少选中一个

编程入门 行业动态 更新时间:2024-10-23 15:33:25
本文介绍了如何验证具有多个复选框的表单以至少选中一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试使用 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 ===

更多推荐

如何验证具有多个复选框的表单以至少选中一个

本文发布于:2023-11-04 01:01:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1556525.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   表单   复选框

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!