คุณสมบัติ valueของ input type="month" คืนค่าและกำหนดค่าปัจจุบันของช่องเลือกเดือน (รูปแบบ YYYY-MM)
รูปแบบ (Syntax)
อ่านค่า:
object.value
กำหนดค่า:
object.value = "YYYY-MM"
ตัวอย่างการใช้งาน
แสดงค่าเดือนที่ผู้ใช้เลือก:
<!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; color: #db133a; font-weight: bold; }
</style>
</head>
<body>
<h1>ตัวอย่าง Input month value property</h1>
<p>สวัสดี เลือกเดือนสำหรับวันหยุดของคุณ</p>
<input type="month" class="monthInput">
<button type="button" onclick="getValue()" class="btn">คลิกเพื่อแสดงค่า</button>
<div class="show"></div>
<script>
function getValue() {
var monthInput = document.querySelector(".monthInput");
document.querySelector(".show").innerHTML = "Value = " + monthInput.value;
}
</script>
</body>
</html>
รูปแบบค่า (Value Format)
ค่าจะอยู่ในรูปแบบ YYYY-MM ตัวอย่าง: 2024-03, 1997-10
การใช้งานจริง
- อ่านค่าที่ผู้ใช้เลือกเพื่อส่งไปเซิร์ฟเวอร์
- ตั้งค่าเริ่มต้นจากข้อมูลผู้ใช้ (profile, settings)
- Validate ค่าก่อนส่งฟอร์ม (เช่น ไม่อนุญาตให้เลือกเดือนในอดีต)
เหตุการณ์ change
monthInput.addEventListener("change", function() {
console.log("เดือนที่เลือก: " + this.value);
});