HTML DOM Input Radio required 屬性


HTML DOM input radio required 屬性與 <input> 元素的 required 屬性相關聯。required 屬性用於設定和返回在表單提交到伺服器之前是否需要選中某個單選按鈕。這允許表單在使用者未選中具有 required 屬性的單選按鈕時不提交。

語法

以下是語法:

設定 required 屬性。

radioObject.required = true|false

這裡,true 表示必須選中單選按鈕,而 false 表示在提交表單之前可以選擇不選中單選按鈕。

示例

讓我們來看一個 input radio 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 按鈕:

在未選中單選按鈕的情況下點選“提交”按鈕:

在上面的例子中:

我們首先建立了一個 id 為“Mango”,name 為“fruits”並且 required 屬性設定為 true 的 input radio 按鈕。該單選按鈕包含在一個表單中,該表單的 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 的 input 元素並獲取其 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";
}

更新於:2021年2月15日

144 次瀏覽

啟動你的 職業生涯

透過完成課程獲得認證

立即開始
廣告