คุณสมบัติ form ของ file upload คืนค่ารีเฟอร์เรนซ์ของอิลิเมนต์ <form> ที่ครอบคลุมช่องอัปโหลดไฟล์
รูปแบบ (Syntax)
object.form
ตัวอย่างการใช้งาน
ระบุว่าช่องอัปโหลดอยู่ในฟอร์มไหน:
<!DOCTYPE html>
<html>
<head>
<style>
body { text-align: center; background-color: #363946; color: #fff; }
form { margin: 2.5rem auto; }
button { background-color: #db133a; border: none; cursor: pointer; padding: 8px 16px; color: #fff; border-radius: 5px; font-size: 1.05rem; }
.show { font-weight: bold; font-size: 1.4rem; }
</style>
</head>
<body>
<h1>ตัวอย่าง form Property</h1>
<form id="Form 1">
<fieldset>
<legend>Form 1</legend>
<input type="file" class="fileUploadBtn">
</fieldset>
</form>
<button onclick="identify()">ระบุฟอร์มของ file input</button>
<p class="show"></p>
<script>
function identify() {
var formId = document.querySelector(".fileUploadBtn").form.id;
document.querySelector(".show").innerHTML = "สวัสดี! ฉันมาจาก " + formId;
}
</script>
</body>
</html>
กรณีที่คืนค่า null
หาก file input ไม่อยู่ภายในแท็ก <form> คุณสมบัติ form จะคืนค่า null
การใช้งานจริง
- ส่งฟอร์มที่มี file input โดยไม่ต้องระบุ form ID
- จัดการหลายฟอร์มในหน้าเดียว
- Validate ไฟล์ก่อนส่งฟอร์มเฉพาะฟอร์มที่เกี่ยวข้อง