HTML DOM Input Radio required 属性

htmlweb developmentfront end technology更新于 2024/5/18 2:20:17

HTML DOM Input Radio required 属性与 <input> 元素的 required 属性相关联。required 属性用于设置并返回在表单提交到服务器之前是否需要选中某些单选按钮。如果用户未选中具有 required 属性的单选按钮,则表单将无法提交。

语法

以下是语法 −

设置 required 属性。

radioObject.required = true|false

其中,true 表示必须选中单选按钮,而 false 表示在提交表单之前可以不选中单选按钮。

示例

让我们看一个输入单选按钮 required 属性的示例 −

<!DOCTYPE html>
<html>
<body>
<h1>Radio required property</h1>
<form style="border:solid 1px green;padding:5px" action="/Sample_page.php">
FRUIT:
<input type="radio" name="fruits" id="Mango" required>Mango
<br><br>
<input type="submit">
</form>
<button type=”button” onclick="checkReq()">CHECK</button>
<p id="Sample"></p>
<script>
   function checkReq() {
      var Req=document.getElementById("Mango").required;
      if(Req==true)
         document.getElementById("Sample").innerHTML="The radio button must be checked before
         submitting";
      else
         document.getElementById("Sample").innerHTML="The radio button is optional and can be
         left unchecked by the user";
   }
</script>
</body>
</html>

输出

这将产生以下输出 −

点击"CHECK"按钮时 −

点击"Submit"按钮且单选按钮未被选中时 −

在上面的例子中 −

我们首先创建了一个输入单选按钮,其 ID 为"Mango",名称为"fruits"并将必需属性设置为 true。单选按钮包含在表单中,该表单包含 action=”Sample_page.php”,用于指定点击提交按钮时提交表单数据的位置。该表单还应用了内联样式 −

<form style="border:solid 1px green;padding:5px" action="/Sample_page.php">
FRUIT:
<input type="radio" name="fruits" id="Mango" required>Mango
<br><br>
<input type="submit">
</form>

然后,我们创建了一个"CHECK"按钮,当用户点击该按钮时,它会执行 checkReq() 方法。

<button type=”button” onclick="checkReq()">CHECK</button>

checkReq() 方法使用 getElementById() 方法获取类型为 radio 的输入元素,并获取其 required 属性,在本例中返回 true。返回的布尔值被赋值给变量 Req,并根据返回值是 true 还是 false,使用其 innerHTML 属性在 id 为"Sample"的段落中显示相应的消息 −

function checkReq() {
   var Req=document.getElementById("Mango").required;
   if(Req==true)
      document.getElementById("Sample").innerHTML="The radio button must be checked before submitting";
   else
      document.getElementById("Sample").innerHTML="The radio button is optional and can be left unchecked by the user";
}

相关文章


有用资源