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

HTML DOM Input Month max Property: เดือนสูงสุดที่เลือกได้

คุณสมบัติ maxของ input type="month" คืนค่าและกำหนดเดือนสูงสุดที่ผู้ใช้สามารถเลือกได้ (รูปแบบ YYYY-MM)

รูปแบบ (Syntax)

อ่านค่า:

object.max

กำหนดค่า:

object.max = "YYYY-MM"

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

จำกัดเลือกเดือนระหว่างเมษายน-สิงหาคม 2019 (เหมือน min property):

<!DOCTYPE html>
<html>
<head>
    <style>
        body { text-align: center; color: #fff; background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) center/cover no-repeat; height: 100vh; }
        p { font-weight: 700; font-size: 1.1rem; }
        input { display: block; width: 35%; border: 2px solid #fff; background-color: transparent; color: #fff; font-weight: bold; padding: 8px; margin: 1rem auto; }
        .btn { background: #0197F6; border: none; height: 2rem; border-radius: 2px; width: 35%; margin: 2rem auto; display: block; color: #fff; outline: none; cursor: pointer; }
        .show { font-size: 1.5rem; font-weight: bold; }
    </style>
</head>
<body>
    <h1>ตัวอย่าง Input month max/min property</h1>
    <p>สวัสดี ต้องการลางานไหม?</p>
    <p>ถ้าใช่ เลือกเดือนระหว่างเมษายนถึงสิงหาคม:</p>
    <input type="month" class="monthInput" min="2019-04" max="2019-08">
    <button onclick="showMySelection()" class="btn">แสดงผล</button>
    <div class="show"></div>
    <script>
        function showMySelection() {
            var monthInput = document.querySelector(".monthInput");
            var showMsg = document.querySelector(".show");
            if (monthInput.value === '') {
                showMsg.innerHTML = "กรุณาเลือก!!";
            } else {
                showMsg.innerHTML = monthInput.value;
            }
        }
    </script>
</body>
</html>

การใช้งานร่วมกับ min

ใช้ min และ max ร่วมกันเพื่อกำหนดช่วงที่เลือกได้:

<!-- เลือกได้แค่ปี 2024 -->
<input type="month" min="2024-01" max="2024-12">

<!-- เลือกได้แค่ 6 เดือนข้างหน้า -->
<input type="month" min="2024-03" max="2024-08">

การตั้งค่าแบบไดนามิกด้วย JavaScript

var today = new Date();
var year = today.getFullYear();
var month = String(today.getMonth() + 1).padStart(2, '0');
var maxDate = year + '-' + month; // เดือนปัจจุบัน
var minDate = (year - 1) + '-' + month; // 1 ปีก่อน

document.querySelector("input[type='month']").min = minDate;
document.querySelector("input[type='month']").max = maxDate;