คุณสมบัติ required ของ HTML DOM input Text เกี่ยวข้องกับแอตทริบิวต์ required ขององค์ประกอบ <input> คุณสมบัติ required ใช้ตั้งค่าและส่งคืนว่าจำเป็นต้องกรอกช่องข้อความบางช่องก่อนส่งฟอร์มไปยังเซิร์ฟเวอร์หรือไม่ นี่ทำให้ฟอร์มไม่ส่งได้หากช่องข้อความที่มีแอตทริบิวต์ required ถูกทิ้งว่างโดยผู้ใช้
ไวยากรณ์
ไวยากรณ์สำหรับการตั้งค่าคุณสมบัติ required:
textObject.required = true|false
ที่นี่ true แทนว่าช่องข้อความต้องถูกกรอก ในขณะที่ false แทนว่าสามารถทิ้งว่างได้ก่อนส่งฟอร์ม
ตัวอย่าง
มาดูตัวอย่างสำหรับคุณสมบัติ required ของ input text:
<!DOCTYPE html> <html> <body> <h1>Input Text required property</h1> <form action="/Sample_page.php"> USERNAME: <input type="text" id="USR" name=”user_name” required> <input type="submit"> </form> <p>ตรวจสอบว่าช่องด้านบนบังคับกรอกหรือไม่โดยคลิกปุ่มด้านล่าง</p> <button onclick="checkReq()">CHECK</button> <p id="Sample"></p> <script> function checkReq() { var Req=document.getElementById("USR").required; if(Req==true) document.getElementById("Sample").innerHTML="The text field must be filled before submitting"; else document.getElementById("Sample").innerHTML="The text field is optional and can be left blank by the user"; } </script> </body> </html>
ผลลัพธ์
จะได้ผลลัพธ์ดังนี้:

เมื่อคลิกปุ่ม CHECK:

หากคุณจะคลิก “Submit” ตอนนี้โดยไม่ป้อน username จะมีคำเตือนและไม่ให้ส่งฟอร์ม:
