Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> HTML

คุณสมบัติ HTML DOM Input Radio checked

คุณสมบัติ checked ของ input type="radio" เกี่ยวข้องกับแอตทริบิวต์ checked ใช้สำหรับ ตั้งค่าหรือดึงค่า สถานะการติ๊กของ radio button ปัจจุบัน

ไวยากรณ์ (Syntax)

การตั้งค่า checked:

radioObject.checked = true|false

ตัวอย่างการใช้งาน

<!DOCTYPE html>
<html>
<body>
<h1>คุณสมบัติ checked ของ Input Radio</h1>
<form>
  ผลไม้: <input type="radio" name="fruits" id="Mango">มะม่วง
  <input type="radio" name="fruits" id="Apple">แอปเปิ้ล
</form>
<br>
<button type="button" onclick="checkApple()">ติ๊กแอปเปิ้ล</button>
<script>
  function checkApple() {
    document.getElementById("Apple").checked = true;
  }
</script>
</body>
</html>

ผลลัพธ์

เริ่มต้น: Radio button ทั้งสองไม่ถูกติ๊ก

คลิก "ติ๊กแอปเปิ้ล": Radio button "แอปเปิ้ล" ถูกติ๊กอัตโนมัติ (มะม่วงจะถูกยกเลิกเพราะ name เหมือนกัน)

คำอธิบายโค้ด

  • มี radio buttons 2 ตัว: id="Mango" และ id="Apple" ชื่อกลุ่มเดียวกัน name="fruits"
  • ปุ่ม "ติ๊กแอปเปิ้ล" เรียก checkApple()
  • document.getElementById("Apple").checked = true ติ๊กแอปเปิ้ลผ่านโปรแกรม

จุดสำคัญ: Radio buttons ที่มี name เหมือนกันจะเป็นกลุ่มเดียวกัน — การติ๊กตัวหนึ่งจะยกเลิกตัวอื่นในกลุ่มอัตโนมัติ คุณสมบัติ checked จึงใช้ควบคุมการเลือกแบบไดนามิกได้