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

前端之家收集整理的这篇文章主要介绍了html – 具有相同名称的多个复选框上的必需属性? [重复]前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > 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,它可以使(几乎)所有浏览器正确地解释表单验证。

原文链接:https://www.f2er.com/html/232608.html

猜你在找的HTML相关文章