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

HTML DOM Input Checkbox checked Property: สถานะการติ๊ก

คุณสมบัติ checked ของ checkbox คืนค่าและกำหนดสถานะการติ๊กปัจจุบัน (true = ติ๊ก, false = ไม่ติ๊ก)

รูปแบบ (Syntax)

อ่านค่า:

object.checked

กำหนดค่า:

object.checked = true | false

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

ควบคุม checkbox ด้วยปุ่ม Yes/No:

<!DOCTYPE html>
<html>
<head>
    <style>
        body { text-align: center; }
        p { font-size: 1.5rem; color: #ff8741; }
        input { width: 30px; height: 30px; }
        button { background-color: #db133a; color: #fff; padding: 8px; border: none; width: 120px; margin: 0.5rem; border-radius: 50px; outline: none; }
    </style>
</head>
<body>
    <h1>ตัวอย่าง checked Property</h1>
    <p>คุณมีความสุขไหม?</p>
    <input type="checkbox"> <br>
    <button onclick="checkYes()">Yes</button>
    <button onclick="checkNo()">No</button>
    <script>
        function checkYes() { document.querySelector("input").checked = true; }
        function checkNo() { document.querySelector("input").checked = false; }
    </script>
</body>
</html>

การใช้งานขั้นสูง

Toggle (สลับสถานะ):

checkbox.checked = !checkbox.checked;

ตรวจสอบสถานะก่อนส่งฟอร์ม:

if (!document.querySelector("#agree").checked) {
    alert("กรุณายอมรับเงื่อนไข");
    return false;
}

เหตุการณ์ที่เกี่ยวข้อง

ใช้ event change เพื่อตรวจจับการเปลี่ยนแปลง:

checkbox.addEventListener("change", function() {
    console.log("สถานะ: " + this.checked);
});