HTML DOM 輸入單選按鈕 checked 屬性


HTML DOM Input 單選按鈕 checked 屬性與 type 為 radio 的 <input> 元素的 checked 屬性相關聯。它用於設定或返回單選按鈕的 checked 屬性值。

語法

以下是語法 −

設定 checked 屬性。

radioObject.checked = true|false

示例

讓我們看一個單選按鈕 checked 屬性的示例 −

即時演示

<!DOCTYPE html>
<html>
<body>
<h1>Input Radio checked property</h1>
<form>
FRUIT:
<input type="radio" name="fruits" id="Mango">Mango
<input type="radio" name="fruits" id="Apple">Apple
</form>
<br><button type=”button” onclick="checkApple()">Check Apple</button>
<script>
   function checkApple() {
      document.getElementById("Apple").checked = true;
   }
</script>
</body>
</html>

輸出

將產生以下輸出 −

單擊“選中蘋果”按鈕 −

在上述示例中 −

在一個表格中包含兩個具有 type=“radio” 和 name=“fruits” 的公共屬性的輸入欄位。第一個單選按鈕的 id 為“芒果”,第二個的 id 為“蘋果” −

<form>
FRUIT:
<input type="radio" name="fruits" id="Mango">Mango
<input type="radio" name="fruits" id="Apple">Apple
</form>

然後建立一個“選中蘋果”按鈕,使用者單擊該按鈕時將執行 checkApple() 方法 −

<button type=”button” onclick="checkApple()">Check Apple</button>

checkApple() 方法使用 getElementById() 方法獲取型別為單選按鈕的輸入元素,並將其 checked 屬性設定為 true。這將選中蘋果單選按鈕: −

function checkApple() {
   document.getElementById("Apple").checked = true;
}

更新於: 15-2-2021

378 個檢視

開啟你的職業生涯

透過學習完成課程認證

開始學習
廣告
© . All rights reserved.