ใช้แท็ก <button> ใน HTML เพื่อเพิ่มปุ่มกด แท็ก HTML <button> ใช้สำหรับสร้างปุ่มภายใน HTML form สามารถใช้แท็ก <input> สร้างปุ่มคล้ายกันได้เช่นกัน
แอตทริบิวต์ของ <button>
| แอตทริบิวต์ | ค่า | คำอธิบาย |
|---|---|---|
| autofocus | autofocus | ระบุว่าปุ่มควรมีโฟกัสเมื่อโหลดหน้า |
| disabled | disabled | ระบุว่าปุ่มถูกปิดใช้งาน |
| form | form_id | ระบุฟอร์มที่ปุ่มเป็นส่วนหนึ่ง (อาจอยู่นอก form) |
| formaction | URL | ระบุลิงก์ที่ฟอร์มส่งไป (override form action) |
| formenctype | application/x-www-form-urlencoded, multipart/form-data, text/plain | ระบุการเข้ารหัสข้อมูลฟอร์มก่อนส่ง (override form enctype) |
| formmethod | get, post | ระบุวิธีส่งข้อมูลฟอร์ม (override form method) |
| formnovalidate | formnovalidate | ระบุว่าไม่ต้อง validate ฟอร์ม (override form novalidate) |
| formtarget | _blank, _self, _parent, _top | ระบุที่เปิดตอบกลับ (override form target) |
| name | Name | ระบุชื่อปุ่ม (ส่งค่าไปกับฟอร์ม) |
| type | button, reset, submit | ระบุประเภทปุ่ม: button=ปุ่มทั่วไป, reset=ล้างฟอร์ม, submit=ส่งฟอร์ม (ค่าเริ่มต้น) |
| value | Text | ระบุค่าเริ่มต้นของปุ่ม (ส่งค่าไปกับฟอร์ม) |
ตัวอย่าง
คุณสามารถลองรันโค้ดต่อไปนี้เพื่อใช้งานแท็ก <button> ใน HTML:
<!DOCTYPE html>
<html>
<head>
<title>HTML Button Tag</title>
</head>
<body>
<form>
<button name="button" value="OK" type="button">ปุ่มของฉัน</button>
</form>
</body>
</html>
ข้อดีของ <button> vs <input type="button">:
- สามารถมีเนื้อหา HTML ภายในได้ (รูปภาพ, ไอคอน, ข้อความหลายบรรทัด)
- จัดสไตล์ด้วย CSS ง่ายกว่า
- แยก value (ที่ส่ง) กับ label (ที่แสดง) ได้ชัดเจน