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

HTML DOM Input Button form Property: ระบุฟอร์มเจ้าของ

คุณสมบัติ form ของ input button คืนค่ารีเฟอร์เรนซ์ของอิลิเมนต์ <form> ที่ครอบคลุมปุ่มนั้นอยู่

รูปแบบ (Syntax)

object.form

ตัวอย่างการใช้งาน

ระบุว่าปุ่มที่คลิกอยู่ในฟอร์มไหน (มี 2 ฟอร์ม):

<!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: 20%; }
        .show-message { font-weight: bold; font-size: 1.4rem; color: #ffc107; }
    </style>
</head>
<body>
    <h1>ตัวอย่าง form Property</h1>
    <form id="form1">
        <fieldset>
            <legend>Form 1</legend>
            <input type="button" class="btn" value="ปุ่ม 1">
            <input type="button" class="btn" value="ปุ่ม 2">
        </fieldset>
    </form>
    <form id="form2">
        <fieldset>
            <legend>Form 2</legend>
            <input type="button" class="btn" value="ปุ่ม 1">
            <input type="button" class="btn" value="ปุ่ม 2">
        </fieldset>
    </form>
    <div class="show-message"></div>
    <script>
        var btnArr = document.querySelectorAll(".btn");
        var showMessage = document.querySelector(".show-message");
        btnArr.forEach(function(ele) {
            ele.addEventListener("click", function(e) {
                showMessage.innerHTML = "";
                if (e.target.form.id === 'form1') {
                    showMessage.innerHTML = "ฉันมาจากฟอร์ม 1";
                } else {
                    showMessage.innerHTML = "ฉันมาจากฟอร์ม 2";
                }
            });
        });
    </script>
</body>
</html>

กรณีที่คืนค่า null

หากปุ่มไม่อยู่ภายในแท็ก <form> คุณสมบัติ form จะคืนค่า null

การใช้งานจริง

  • จัดการปุ่มหลายฟอร์มในหน้าเดียวด้วย event handler เดียว
  • ส่งข้อมูลฟอร์มที่ถูกต้องโดยไม่ต้องระบุ ID ฟอร์มแต่ละปุ่ม
  • ตรวจสอบความถูกต้องของฟอร์มก่อนส่ง (validation)