加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 资源网站 > 资源 > 正文

html – 具有相同名称的多个复选框上的必需属性? [重复]

发布时间:2020-12-14 21:26:18 所属栏目:资源 来源:网络整理
导读:参见英文答案 Using the HTML5 “required” attribute for a group of checkboxes?9个答案我有一个具有相同名称属性的复选框列表,我需要验证其中至少有一个已被选中。 但是当我在所有这些属性上使用html5属性“required”时,浏览器(chrome ff)不允许我提
参见英文答案 > Using the HTML5 “required” attribute for a group of checkboxes?9个答案我有一个具有相同名称属性的复选框列表,我需要验证其中至少有一个已被选中。

但是当我在所有这些属性上使用html5属性“required”时,浏览器(chrome& ff)不允许我提交表单,除非检查所有这些属性。

示例代码:

<label for="a-0">a-0</label>
<input type="checkbox" name="q-8" id="a-0" required />
<label for="a-1">a-1</label>
<input type="checkbox" name="q-8" id="a-1" required />
<label for="a-2">a-2</label>
<input type="checkbox" name="q-8" id="a-2" required />

当使用相同的无线电输入时,表单按预期工作(如果选择其中一个选项,表单验证)

根据Joe Hopfgartner(声称引用html5规范),假设的行为是:

For checkboxes,the required attribute shall only be satisfied when one or more of the checkboxes with that name in that form are checked.

For radio buttons,the required attribute shall only be satisfied when exactly one of the radio buttons in that radio group is checked.

我做错了什么,或者这是一个浏览器错误(在chrome和amp; ff上)?

解决方法

对不起,现在我已经更好地阅读了您的期望,所以我正在更新答案。

基于W3C的HTML5 Specs,没有错。我创建了this JSFiddle test,它根据规格正确运行(对于那些基于规格的浏览器,如Chrome 11和Firefox 4):

<form>
    <input type="checkbox" name="q" id="a-0" required autofocus>
    <label for="a-0">a-1</label>
    <br>

    <input type="checkbox" name="q" id="a-1" required>
    <label for="a-1">a-2</label>
    <br>

    <input type="checkbox" name="q" id="a-2" required>
    <label for="a-2">a-3</label>
    <br>

    <input type="submit">
</form>

我同意它不是很有用(实际上很多人在W3C’s mailing lists都抱怨过它)。

但浏览器只是遵循标准的建议,这是正确的。该标准有点误导,但在实践中我们无法做任何事情。但是,您可以随时使用JavaScript进行表单验证,就像一些优秀的jQuery验证插件一样。

另一种方法是选择polyfill,它可以使(几乎)所有浏览器正确地解释表单验证。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读