HTML DOM Input Button Object แทนอิลิเมนต์ <input type="button"> ใช้สร้างและจัดการปุ่มผ่าน JavaScript
รูปแบบการสร้าง (Syntax)
var newButton = document.createElement("INPUT");
newButton.setAttribute("type", "button"); // หรือ "submit", "reset"
คุณสมบัติหลัก (Properties)
| คุณสมบัติ | คำอธิบาย |
|---|---|
| autofocus | คืนค่าและกำหนดโฟกัสอัตโนมัติ |
| defaultValue | คืนค่าและแก้ไขค่าเริ่มต้นของปุ่ม |
| disabled | คืนค่าและกำหนดสถานะปิดใช้งาน |
| form | คืนค่ารีเฟอร์เรนซ์ของฟอร์มที่ครอบคลุมปุ่ม |
| name | คืนค่าและแก้ไขแอตทริบิวต์ name |
| type | คืนค่าประเภทปุ่ม (button, submit, reset) |
| value | คืนค่าและแก้ไขข้อความบนปุ่ม |
ตัวอย่างการใช้งาน
สร้างปุ่มเลียนแบบ (replicate) เมื่อคลิก:
<!DOCTYPE html>
<html>
<head>
<style>
body { text-align: center; }
.btn { display: block; margin: 1rem auto; background-color: #db133a; color: #fff; border: 1px solid #db133a; padding: 0.5rem; border-radius: 50px; width: 60%; font-weight: bold; }
.show-msg { font-weight: bold; font-size: 1.4rem; color: #ffc107; }
</style>
</head>
<body>
<h1>ตัวอย่าง Input Button Object</h1>
<input type="button" onclick="createReplica()" class="btn" value="คลิกเพื่อเลียนแบบฉัน">
<div class="show-msg"></div>
<script>
function createReplica() {
var newButton = document.createElement("INPUT");
newButton.setAttribute("type", "button");
newButton.setAttribute("class", "btn");
newButton.setAttribute("value", "คลิกเพื่อเลียนแบบฉัน");
newButton.setAttribute("onclick", "createReplica()");
document.body.appendChild(newButton);
}
</script>
</body>
</html>
ประเภทปุ่ม (type attribute)
| ประเภท | คำอธิบาย |
|---|---|
| button | ปุ่มทั่วไป ไม่มีพฤติกรรมเริ่มต้น ต้องใช้ JS ควบคุม |
| submit | ส่งฟอร์ม (พฤติกรรมเริ่มต้น) |
| reset | รีเซ็ตฟอร์มกลับค่าเริ่มต้น |