我只是想知道如何在单选按钮上以正确的方式使用新的 HTML5 输入属性“必需”。每个单选按钮字段是否都需要像下面这样的属性,或者如果只有一个字段获得它就足够了?
<input type="radio" name="color" value="black" required="required" />
<input type="radio" name="color" value="white" required="required" />
TL;DR:为 radio 组的至少一个输入设置 required
属性。
为所有输入设置 required
更加清晰,但不是必需的(除非动态生成单选按钮)。
要对单选按钮进行分组,它们必须具有相同的 name
值。这允许一次只选择一个并将 required
应用于整个组。
<form>
Select Gender:<br>
<label>
<input type="radio" name="gender" value="male" required>
Male
</label><br>
<label>
<input type="radio" name="gender" value="female">
Female
</label><br>
<label>
<input type="radio" name="gender" value="other">
Other
</label><br>
<input type="submit">
</form>
还要注意:
To avoid confusion as to whether a radio button group is required or not, authors are encouraged to specify the attribute on all the radio buttons in a group. Indeed, in general, authors are encouraged to avoid having radio button groups that do not have any initially checked controls in the first place, as this is a state that the user cannot return to, and is therefore generally considered a poor user interface.
Source
我是一名优秀的程序员,十分优秀!