如何使用“必需的”具有“radio”的属性输入字段
我只是想知道如何在单选按钮上以正确的方式使用新的 HTML5 输入属性“required”。是否每个单选按钮字段都需要如下所示的属性,还是只有一个字段获取该属性就足够了?
<input type="radio" name="color" value="black" required="required" />
<input type="radio" name="color" value="white" required="required" />
I am just wondering how to use the new HTML5 input attribute "required" in the right way on radio buttons. Does every radio button field need the attribute like below or is it sufficient if only one field gets it?
<input type="radio" name="color" value="black" required="required" />
<input type="radio" name="color" value="white" required="required" />
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
TL;DR:为单选组的至少一个输入设置
required
属性。为所有输入设置
required
更清晰,但不是必要的(除非动态生成单选按钮)。要对单选按钮进行分组,它们必须具有相同的
name
值。这样一次只能选择一个,并将required
应用于整个组。另请注意:
来源
TL;DR: Set the
required
attribute for at least one input of the radio group.Setting
required
for all inputs is more clear, but not necessary (unless dynamically generating radio-buttons).To group radio buttons they must all have the same
name
value. This allows only one to be selected at a time and appliesrequired
to the whole group.Also take note of:
Source
我必须使用
required="required"
以及相同的名称和类型,然后验证工作正常。I had to use
required="required"
along with the same name and type, and then validation worked fine.以下是具有本机 HTML5 验证的所需单选按钮的非常基本但现代的实现:
尽管我非常喜欢使用本机 HTML5 验证的简约方法,但从长远来看,您可能希望将其替换为 Javascript 验证。 Javascript 验证使您可以更好地控制验证过程,并且允许您设置真实的类(而不是伪类)来改进(输入)有效字段的样式。如果 Javascript 损坏(或缺少),此原生 HTML5 验证可以作为您的后备方案。您可以在此处找到相关示例,以及有关如何制作更好的表单,灵感来自 安德鲁·科尔。
Here is a very basic but modern implementation of required radio buttons with native HTML5 validation:
Although I am a big fan of the minimalistic approach of using native HTML5 validation, you might want to replace it with Javascript validation on the long run. Javascript validation gives you far more control over the validation process and it allows you to set real classes (instead of pseudo classes) to improve the styling of the (in)valid fields. This native HTML5 validation can be your fall-back in case of broken (or lack of) Javascript. You can find an example of that here, along with some other suggestions on how to make Better forms, inspired by Andrew Cole.
您可以使用此代码片段...
在其中一个选择语句中指定“required”关键字。如果你想改变它的默认外观方式。您可以按照以下步骤操作。如果您打算修改默认行为,这只是为了提供额外信息。
将以下内容添加到您的
.css
文件中。欲了解更多信息,您可以参考以下网址。
https://css-tricks.com/almanac/selectors/r/required/
You can use this code snippet ...
Specify "required" keyword in one of the select statements. If you want to change the default way of its appearance. You can follow these steps. This is just for extra info if you have any intention to modify the default behavior.
Add the following into you
.css
file.For more information you can refer following URL.
https://css-tricks.com/almanac/selectors/r/required/