คุณสมบัติ defaultValue ของ input type="month" คืนค่าและกำหนดค่าเริ่มต้นของช่องเลือกเดือน (ค่าที่อยู่ใน HTML ตอนโหลดหน้า)
รูปแบบ (Syntax)
อ่านค่า:
object.defaultValue
กำหนดค่า:
object.defaultValue = "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.2rem; }
input { width: 35%; border: 2px solid #fff; background-color: transparent; color: #fff; font-weight: bold; padding: 8px; }
.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 defaultValue</h1>
<p>สวัสดี กรอกเดือนเกิดของคุณ</p>
<input type="month" class="monthInput">
<button onclick="changeValue()" class="btn">ส่ง</button>
<div class="show"></div>
<script>
function changeValue() {
var monthInput = document.querySelector(".monthInput");
var showMsg = document.querySelector(".show");
monthInput.defaultValue = "1997-10";
monthInput.value = monthInput.defaultValue;
showMsg.innerHTML = ":D เข้าๆ ฉันเปลี่ยนเดือนเกิดคุณเป็นของฉันแล้ว!";
}
</script>
</body>
</html>
ความแตกต่างระหว่าง value และ defaultValue
| คุณสมบัติ | คำอธิบาย |
|---|---|
| value | ค่าปัจจุบัน (เปลี่ยนเมื่อผู้ใช้เลือก) |
| defaultValue | ค่าเริ่มต้นตอนโหลดหน้า (ไม่เปลี่ยนเอง) |
การใช้งานจริง
- รีเซ็ตฟอร์มกลับค่าเริ่มต้น:
input.value = input.defaultValue - ตรวจสอบว่าผู้ใช้เปลี่ยนค่าจากค่าเริ่มต้นหรือไม่
- กำหนดค่าเริ่มต้นแบบไดนามิกจากข้อมูลเซิร์ฟเวอร์