Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> HTML

แท็ก input: สร้างฟิลด์ป้อนข้อมูลใน HTML (คู่มือครบถ้วน)

แท็ก <input> เป็นองค์ประกอบหลักสำหรับรับข้อมูลจากผู้ใช้ในฟอร์ม HTML รองรับหลายประเภท (type) และมีแอตทริบิวต์มากมายสำหรับควบคุมพฤติกรรม

แอตทริบิวต์สำคัญ (สรุป)

แอตทริบิวต์ คำอธิบาย
type ประเภทอินพุท (text, password, email, number, date, checkbox, radio, file, submit, button, hidden, color, range, search, tel, url, dll.)
name ชื่อฟิลด์ (สำคัญสำหรับส่งข้อมูลฟอร์ม)
value ค่าเริ่มต้น
placeholder ข้อความแนะนำ (หายเมื่อพิมพ์)
required บังคับกรอก
disabled ปิดใช้งาน
readonly อ่านอย่างเดียว (ส่งค่าได้)
maxlength / minlength จำนวนตัวอักษรสูงสุด/ต่ำสุด
min / max / step ค่าต่ำสุด/สูงสุด/ขั้นตอน (สำหรับ number, date, range)
pattern Regex สำหรับตรวจสอบรูปแบบ
autocomplete on/off - ควบคุมการเติมอัตโนมัติ
autofocus โฟกัสอัตโนมัติเมื่อโหลดหน้า
list เชื่อมกับ <datalist> สำหรับ autocomplete
multiple อนุญาตหลายค่า (file, email)
accept ชนิดไฟล์ที่ยอมรับ (สำหรับ type="file")
capture user/environment - ควบคุมกล้อง (mobile)
form เชื่อมกับ form ID อื่นนอกจากฟอร์มตัวเอง
formaction, formenctype, formmethod, formtarget, formnovalidate ออเวอร์ไรด์แอตทริบิวต์ของ form (สำหรับ type="submit/image")

ประเภท Input พิเศษ HTML5

  • email - ตรวจสอบรูปแบบอีเมลอัตโนมัติ
  • tel - เบอร์โทร (แสดงคีย์บอร์ดตัวเลขบนมือถือ)
  • url - ตรวจสอบรูปแบบ URL
  • number - ตัวเลข พร้อม spinner
  • range - สไลเดอร์เลือกค่า
  • date, datetime-local, month, week, time - Date/Time picker
  • color - Color picker
  • search - กล่องค้นหา (มีปุ่ม clear บางเบราว์เซอร์)

ตัวอย่างฟอร์มทั่วไป

<!DOCTYPE html>
<html>
<head>
    <title>ตัวอย่าง HTML input Tag</title>
</head>
<body>
    <form action="/submit" method="post">
        <label>ชื่อ: <input type="text" name="first_name" maxlength="100" required></label><br>
        <label>นามสกุล: <input type="text" name="last_name" maxlength="100" required></label><br>
        <label>อีเมล: <input type="email" name="email" required></label><br>
        <label>อายุ: <input type="number" name="age" min="1" max="120"></label><br>
        <input type="submit" value="ส่งข้อมูล">
    </form>
</body>
</html>

แนวทางปฏิบัติที่ดี

  • ใช้ <label> ผูกกับ input ด้วย for / id เพื่อ Accessibility
  • ระบุ type ให้ถูกต้องเพื่อ UX ดีที่สุดบนมือถือ
  • ใช้ required, pattern, min/max สำหรับ Validationฝั่ง Client
  • Validate ฝั่ง Server เสมอ (Client-side ข้ามได้)