ออบเจ็กต์ HTML DOM Input Radio เกี่ยวข้องกับ <input type="radio"> สามารถสร้างและเข้าถึงได้ด้วย createElement() และ getElementById()
คุณสมบัติ (Properties)
| # | คุณสมบัติและคำอธิบาย |
|---|---|
| 1 | autofocus — โฟกัสอัตโนมัติเมื่อโหลดหน้า |
| 2 | checked — สถานะการติ๊ก (ตั้งค่า/ดึงค่าได้) |
| 3 | defaultChecked — ค่าเริ่มต้นของแอตทริบิวต์ checked |
| 4 | defaultValue — ค่าเริ่มต้นของ value attribute |
| 5 | disabled — สถานะ disabled |
| 6 | form — อ้างอิงฟอร์มที่บรรจุ radio button |
| 7 | name — name attribute |
| 8 | required — สถานะ required |
| 9 | type — (อ่านอย่างเดียว) คืนค่า "radio" |
| 10 | value — value attribute |
ไวยากรณ์การสร้าง
var R = document.createElement("INPUT");
R.setAttribute("type", "radio");
ตัวอย่าง: สร้าง Radio Button แบบไดนามิก
<!DOCTYPE html>
<html>
<head>
<script>
function createRadio() {
var R = document.createElement("INPUT");
R.setAttribute("type", "radio");
document.body.appendChild(R);
}
</script>
</head>
<body>
<h1>ออบเจ็กต์ Input Radio</h1>
<p>คลิกปุ่มด้านล่างเพื่อสร้าง radio button</p>
<button type="button" onclick="createRadio()">สร้าง</button>
<br><br>
มะม่วง:
</body>
</html>
ผลลัพธ์
ก่อนคลิก: ไม่มี radio button
หลังคลิก "สร้าง": Radio button ใหม่ปรากฏขึ้น พร้อมข้อความ "มะม่วง:" นำหน้า
คำอธิบายโค้ด
- ปุ่ม "สร้าง" เรียก
createRadio() createElement("INPUT")สร้าง input elementsetAttribute("type", "radio")กำหนด typeappendChild()เพิ่มเข้า body
หมายเหตุ: ตัวอย่างโค้ดต้นฉบับมีข้อผิดพลาดเล็กน้อย (ใช้ createPASS แทน createRadio) — โค้ดด้านบนได้แก้ไขแล้ว