使用HTML5“必需”属性为一组复选框? [英] Using the HTML5 "required" attribute for a group of checkboxes?

查看:175
本文介绍了使用HTML5“必需”属性为一组复选框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用支持HTML5的较新的浏览器(例如FireFox 4);

和一个表单字段有属性 required ='required' ;

,表单字段为空/空白;

,并点击提交按钮;

浏览器检测到必填字段为空,不提交表单;
而是浏览器显示一个提示,要求用户在该字段中键入文本。

When using the newer browsers that support HTML5 (FireFox 4 for example);
and a form field has the attribute required='required';
and the form field is empty/blank;
and the submit button is clicked;
the browsers detects that the "required" field is empty and does not submit the form;
instead browser shows a hint asking the user to type text into the field.

现在,不是单个文本字段

Now, instead of a single text field, I have a group of checkboxes, out of which at least one should be checked/selected by the user.

如何使用HTML5 <$

How can I use the HTML5 required attribute on this group of checkboxes? (Since only one of the checkboxes needs to be checked, I can't put the required attribute on each and every checkbox)

ps。我使用 simple_form ,如果这很重要。

ps. I am using simple_form, if that matters.

UPDATE

HTML 5 multiple 属性?以前有人使用它来做类似我的问题吗?

Could the HTML 5 multiple attribute be helpful here? Has anyone use it before for doing something similar to my question?

>显示 HTML5规范不支持此功能 ISSUE -111:什么是输入?@必需是什么意思是@type =复选框?

It appears that this feature is not supported by the HTML5 spec: ISSUE-111: What does input.@required mean for @type = checkbox?

(发布状态:
这里是解释

推荐答案

不幸的是,HTML5并没有提供开箱即用的方法。

Unfortunately HTML5 does not provide an out-of-the-box way to do that.

但是,使用jQuery可以很容易地控制复选框组中是否至少有一个选中的元素。

However, using jQuery, you can easily control if a checkbox group has at least one checked element.

考虑下面的DOM片段: p>

Consider the following DOM snippet:

<div class="checkbox-group required">
    <input type="checkbox" name="checkbox_name[]">
    <input type="checkbox" name="checkbox_name[]">
    <input type="checkbox" name="checkbox_name[]">
    <input type="checkbox" name="checkbox_name[]">
</div>

您可以使用此表达式:

$('div.checkbox-group.required :checkbox:checked').length > 0

如果至少有一个会返回 true 元素。
基于此,你可以实现你的验证检查。

which returns true if at least one element is checked. Based on that, you can implement your validation check.

这篇关于使用HTML5“必需”属性为一组复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆