แอตทริบิวต์ formaction ใช้ใน <button type="submit"> หรือ <input type="submit"> เพื่อ ออเวอร์ไรด์ แอตทริบิวต์ action ของ <form> สำหรับปุ่มนั้นๆ เฉพาะ ใช้ได้ใน HTML5
ตัวอย่างการใช้งาน
<!DOCTYPE html>
<html>
<head>
<title>ตัวอย่าง HTML formaction attribute</title>
</head>
<body>
<form action="/new1.php" method="get">
<label>ชื่อนักศึกษา: <input type="text" name="name"></label><br>
<label>วิชา: <input type="text" name="subject"></label><br>
<button type="submit">บันทึกปกติ (ไป /new1.php)</button><br>
<button type="submit" formaction="/new2.php">บันทึกไปหน้าอื่น (ไป /new2.php)</button>
<button type="submit" formaction="/preview.php" formmethod="post">ดูตัวอย่าง (POST ไป /preview.php)</button>
</form>
</body>
</html>
แอตทริบิวต์ Form Override อื่นๆ (ใช้กับ Submit Buttons)
| แอตทริบิวต์ | ออเวอร์ไรด์ | คำอธิบาย |
|---|---|---|
| formaction | form.action | URL ปลายทาง |
| formmethod | form.method | GET / POST |
| formenctype | form.enctype | application/x-www-form-urlencoded, multipart/form-data, text/plain |
| formtarget | form.target | _blank, _self, _parent, _top, framename |
| formnovalidate | form.novalidate | ข้าม Validation |
กรณีการใช้งานจริง
- Save vs Save & Continue: ปุ่มต่างกัน ส่งไป Endpoint ต่างกัน
- Preview: ส่งไปหน้า Preview (POST) แทนที่จะบันทึกจริง
- Export: ปุ่ม Export PDF/Excel ส่งไป Endpoint ต่าง
- Delete: ปุ่มลบใน Form แก้ไข (formaction="/delete" formmethod="post")
ตัวอย่างครบ: ปุ่มหลายฟังก์ชันใน Form เดียว
<form action="/articles" method="post" id="articleForm">
<textarea name="content" required></textarea>
<button type="submit" name="action" value="draft">บันทึกร่าง</button>
<button type="submit" name="action" value="publish" formaction="/articles/publish">เผยแพร่</button>
<button type="submit" name="action" value="preview" formaction="/articles/preview" formtarget="_blank">ดูตัวอย่าง</button>
<button type="submit" name="action" value="delete" formaction="/articles/delete" formmethod="post" formnovalidate>ลบ</button>
</form>