如何在单选框输入字段中使用"Required"属性?
带有 type 属性 "radio" 的 HTML 输入元素表示一个选项,该选项来自一个组,该组中最多只能同时选择一个选项。这些组通常由多个单选按钮定义,每个单选按钮的 name 属性值相同。选中单选按钮时,通常会呈现为一个填充或高亮的小圆圈。
与复选框控件不同,单选按钮严重依赖于 value 属性。在 HTML 中提交表单时,只有选中的选项会随表单一起发送给处理代理,处理代理除了检查提交控件的值之外,没有其他方法来确定选择了哪个选项。这就是为什么每个选项的 value 属性在组内应该不同的原因。
要分配到同一个组,一组单选按钮的 name 属性值必须全部相同。一组单选按钮必须位于同一文档中并属于同一表单,否则它们必须完全不存在。将单选按钮放置在不同的表单或文档中会导致它们分离。
除了适用于所有 <input> 元素的通用属性外,单选按钮输入还支持以下属性。
checked: 布尔值属性,指示此单选按钮是否为组中的默认选中按钮。
value: 提交表单时,只有当前选中的单选按钮才会发送到服务器,报告的值是 value 属性的值。如果未指定其他值,则默认使用字符串 on。
required: required 属性是大多数 <input> 元素共享的属性。如果同名单选按钮组中的任意一个单选按钮具有 required 属性,则必须选中该组中的单选按钮,即使该按钮未应用该属性。
示例
让我们看一个包含表单内单选按钮的示例。
<!DOCTYPE html>
<html>
<head>
<title> Simple form with radio buttons </title>
</head>
<body>
<form action= "" method= "GET">
<h4> Choose your age group </h4>
<label>
<input type= "radio" name= "age" value= "children">0-17
</label>
<br>
<label>
<input type= "radio" name= "age" value= "young">18-35
</label>
<br>
<label>
<input type= "radio" name= "age" value= "middle-aged">36-55
</label>
<br>
<label>
<input type= "radio" name= "age" value= "old">56+
</label>
<br><br>
<input type= "submit" onclick= "acknowledge()">
</form>
<script>
function acknowledge(){
alert(" The form has been submitted successfully. ")
}
</script>
</body>
</html>
正如我们所观察到的,即使没有从选项列表中选择单选按钮,表单也可以提交。我们可以通过在单选输入框上使用"required"属性来解决这个问题。
在单选输入框中使用"required"属性
为所有输入框设置required属性似乎更明显,但如果我们不需要动态生成单选按钮,则没有必要。要对单选按钮进行分组,它们应该都具有相同的 name 属性值。这样,我们就可以一次只选择一个单选按钮,并将必需的属性应用于整个组。让我们看一个相同的示例。
示例
在此示例中,我们创建一个包含单选输入框的表单,并将必需的属性应用于单选输入框。
<!DOCTYPE html>
<html>
<head>
<title> How to Use the "required" Attribute with the Radio Input Field </title>
<style>
form{
width: 550px;
margin: 10px;
background-color: lemonchiffon;
color: indigo;
font-size: 18px;
}
input{
margin: 10px;
}
#btn{
width: 60px;
height: 30px;
background-color: thistle;
color: azure;
font-weight: bold;
border: 0;
}
#btn:hover{
background-color: indigo;
}
</style>
</head>
<body>
<h3> Choose the correct answer </h3>
<form action= "" method= "GET">
<label>
<input type= "radio" name= "answer" value= "1" required>Java is a low-level language.
</label>
<br>
<label>
<input type= "radio" name= "answer" value= "2">Python does not support object-oriented programming.
</label>
<br>
<label>
<input type= "radio" name= "answer" value= "3">C is one of the most common and widely used programming languages.
</label>
<br>
<label>
<input type= "radio" name= "answer" value= "4">C is the preferred language for competitive programming.
</label>
<br>
<input type= "submit" id= "btn">
</form>
</body>
</html>
当用户尝试提交表单而不选中单选按钮时,必需属性会生成警告消息并阻止表单提交。
相关文章
有用资源
html 参考教程 - 该教程包含有关 html 的更多信息:https://www.cainiaomax.com/html/

