ฟอร์มเป็นช่องทางรับข้อมูลจากผู้ใช้ เช่น สมัครสมาชิก ค้นหา ส่งความคิดเห็น อัปโหลดไฟล์ หรือเข้าสู่ระบบ การสร้างฟอร์มที่ดีต้องคำนึงถึงโครงสร้าง การเชื่อม label กับ input การตรวจสอบข้อมูล และ accessibility
<form action="" method="get/post"><form> ครอบกลุ่ม input ที่จะส่งข้อมูลไปยังปลายทาง
<form action="/register" method="post">
...
</form>
method ที่ใช้บ่อย:
get: ส่งข้อมูลผ่าน query string เหมาะกับการค้นหาpost: ส่งข้อมูลใน request body เหมาะกับข้อมูลที่สร้างหรือเปลี่ยนแปลงระบบ<input type="">input มีหลายชนิดตามประเภทข้อมูล
<input type="text" name="fullname">
<input type="email" name="email">
<input type="password" name="password">
<input type="number" name="age">
<input type="date" name="birthdate">
<input type="checkbox" name="accept">
<input type="radio" name="level" value="beginner">
<input type="file" name="avatar">
การเลือก type ที่ถูกต้องช่วยให้ browser แสดง UI ที่เหมาะสม และช่วยตรวจสอบข้อมูลเบื้องต้นได้
<label for="">label ช่วยให้ผู้ใช้เข้าใจว่า input ใช้กรอกอะไร และช่วย accessibility เพราะ screen reader สามารถอ่านความสัมพันธ์ระหว่าง label กับ input ได้
<label for="email">อีเมล</label>
<input id="email" type="email" name="email">
เมื่อคลิก label cursor จะ focus ไปที่ input ที่เชื่อมกัน
<select> และ <option>ใช้สร้าง dropdown menu
<label for="course">เลือกรายวิชา</label>
<select id="course" name="course">
<option value="">-- เลือก --</option>
<option value="web">การโปรแกรมบนเว็บ</option>
<option value="database">ฐานข้อมูล</option>
</select>
<textarea>ใช้รับข้อความหลายบรรทัด
<label for="message">ข้อความ</label>
<textarea id="message" name="message" rows="5" cols="40"></textarea>
<button>ปุ่มในฟอร์มควรกำหนด type ให้ชัดเจน
<button type="submit">ส่งข้อมูล</button>
<button type="reset">ล้างฟอร์ม</button>
<button type="button">ตรวจสอบ</button>
HTML5 มี attribute สำหรับตรวจสอบข้อมูลเบื้องต้น
<input type="text" name="username" required maxlength="20">
<input type="number" name="score" min="0" max="100">
<input type="text" name="studentId" pattern="[0-9]{10}">
| Attribute | ความหมาย |
|---|---|
| required | ต้องกรอก |
| min/max | ค่าน้อยสุด/มากสุด |
| pattern | รูปแบบที่ต้องตรงกับ regular expression |
| maxlength | จำนวนตัวอักษรสูงสุด |
<form action="/contact" method="post">
<label for="name">ชื่อ</label>
<input id="name" name="name" type="text" required maxlength="60">
<label for="email">อีเมล</label>
<input id="email" name="email" type="email" required>
<label for="message">ข้อความ</label>
<textarea id="message" name="message" rows="5" required></textarea>
<button type="submit">ส่งข้อความ</button>
</form>
สร้างฟอร์มสมัครเรียนที่มีชื่อ อีเมล รหัสผ่าน อายุ วันเกิด ระดับความรู้เดิม รายวิชาที่สนใจ และปุ่ม submit
method="get" และ method="post" ต่างกันอย่างไรlabel for เชื่อมกับ input idemail ช่วยอะไรrequired และ maxlength ใช้ทำอะไรtextarea ต่างจาก input type="text" อย่างไร