คุณสมบัติ requiredของ input type="number" คืนค่าและกำหนดว่าช่องกรอกตัวเลขบังคับต้องกรอกก่อนส่งฟอร์มหรือไม่
รูปแบบ (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 number required property</h1>
<form action="">
<p>สวัสดี ใส่วันเกิดของคุณ (ตัวเลข)</p>
<input type="number" class="numberInput" required>
<input type="submit" onclick="checkInput()">
</form>
<div class="show"></div>
<script>
function checkInput() {
var numberInput = document.querySelector(".numberInput");
if (numberInput.value === '') {
document.querySelector(".show").innerHTML = "กรุณาเลือก";
}
}
</script>
</body>
</html>
พฤติกรรมของเบราว์เซอร์
- เบราว์เซอร์จะบล็อกการส่งฟอร์มและแสดงข้อความแจ้งเตือนอัตโนมัติ
- ยังตรวจสอบว่าเป็นตัวเลขที่ถูกต้องอีกด้วย (ตาม min, max, step)
- สามารถปรับแต่งข้อความได้ด้วย
setCustomValidity()
การใช้งานร่วมกับ min/max/step
<input type="number" min="1" max="31" step="1" required>
จะบังคับให้กรอกตัวเลข 1-31 เท่านั้น