คุณสมบัติ requiredของ input type="month" คืนค่าและกำหนดว่าช่องเลือกเดือนบังคับต้องกรอกก่อนส่งฟอร์มหรือไม่
รูปแบบ (Syntax)
อ่านค่า:
object.required
กำหนดค่า:
object.required = true | false
ตัวอย่างการใช้งาน
ฟอร์มที่บังคับให้เลือกเดือนเกิด:
<!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 required property</h1>
<form action="">
<p>สวัสดี เลือกเดือนเกิดของคุณ?</p>
<input type="month" class="monthInput" required>
<input type="submit" onclick="checkInput()">
</form>
<div class="show"></div>
<script>
function checkInput() {
var monthInput = document.querySelector(".monthInput");
if (monthInput.value === '') {
document.querySelector(".show").innerHTML = "กรุณาเลือกเดือน";
}
}
</script>
</body>
</html>
พฤติกรรมของเบราว์เซอร์
- เบราว์เซอร์จะบล็อกการส่งฟอร์มและแสดงข้อความแจ้งเตือนอัตโนมัติ
- ข้อความขึ้นอยู่กับเบราว์เซอร์และภาษา
- สามารถปรับแต่งข้อความได้ด้วย
setCustomValidity()
การปรับแต่งข้อความแจ้งเตือน
var monthInput = document.querySelector("input[type='month']");
monthInput.addEventListener("invalid", function() {
if (this.validity.valueMissing) {
this.setCustomValidity("กรุณาเลือกเดือนเกิดของคุณ");
}
});
monthInput.addEventListener("change", function() {
this.setCustomValidity("");
});