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

ออบเจ็กต์ HTML DOM Input Radio

ออบเจ็กต์ HTML DOM Input Radio เกี่ยวข้องกับ <input type="radio"> สามารถสร้างและเข้าถึงได้ด้วย createElement() และ getElementById()

คุณสมบัติ (Properties)

#คุณสมบัติและคำอธิบาย
1autofocus — โฟกัสอัตโนมัติเมื่อโหลดหน้า
2checked — สถานะการติ๊ก (ตั้งค่า/ดึงค่าได้)
3defaultChecked — ค่าเริ่มต้นของแอตทริบิวต์ checked
4defaultValue — ค่าเริ่มต้นของ value attribute
5disabled — สถานะ disabled
6form — อ้างอิงฟอร์มที่บรรจุ radio button
7name — name attribute
8required — สถานะ required
9type — (อ่านอย่างเดียว) คืนค่า "radio"
10value — 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 ใหม่ปรากฏขึ้น พร้อมข้อความ "มะม่วง:" นำหน้า

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

  1. ปุ่ม "สร้าง" เรียก createRadio()
  2. createElement("INPUT") สร้าง input element
  3. setAttribute("type", "radio") กำหนด type
  4. appendChild() เพิ่มเข้า body

หมายเหตุ: ตัวอย่างโค้ดต้นฉบับมีข้อผิดพลาดเล็กน้อย (ใช้ createPASS แทน createRadio) — โค้ดด้านบนได้แก้ไขแล้ว