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

วิธีแสดงคำแนะนำสั้น (Placeholder) ใน HTML

ใช้แอตทริบิวต์ placeholder ใน HTML เพื่อแสดงคำแนะนำสั้นๆ อธิบายค่าที่คาดหวังขององค์ประกอบ Placeholder จะหายเมื่อผู้ใช้เริ่มพิมพ์

ตัวอย่าง

ลองรันโค้ดต่อไปนี้เพื่อใช้งานแอตทริบิวต์ placeholder:

<!DOCTYPE html>
<html>
  <body>
    <h2>Login</h2>
    <form action="/new.php">
      <input type="text" placeholder="Student UserName" name="name"><br>
      <input type="password" placeholder="Password" name="password"><br><br>
      <input type="submit" value="Submit">
    </form>
  </body>
</html>

องค์ประกอบที่รองรับ placeholder

  • <input>: text, search, url, tel, email, password, number, date, time, etc.
  • <textarea>
  • ไม่รองรับ: select, checkbox, radio, file, hidden, button, submit

Placeholder vs Label (สำคัญมาก)

⚠️ Placeholder ไม่ใช่ Label! Placeholder หายเมื่อพิมพ์ ไม่เข้าถึงได้ด้วย Screen Reader บางตัว และไม่ใช่การเข้าถึง (Accessible) ให้ใช้ <label> เสมอ

❌ ผิด - ใช้ Placeholder แทน Label

<input type="email" placeholder="Email">

✅ ถูกต้อง - ใช้ Label + Placeholder

<label for="email">Email</label>
<input type="email" id="email" name="email" placeholder="you@example.com">

✅ ถูกต้อง - Floating Label Pattern (CSS only)

<div class="form-group">
  <input type="text" id="name" name="name" required placeholder=" ">
  <label for="name">Name</label>
</div>

<style>
.form-group { position: relative; margin: 1.5rem 0; }
.form-group input { width: 100%; padding: 0.5rem 0; border: none; border-bottom: 2px solid #ccc; background: transparent; }
.form-group label { position: absolute; top: 0.5rem; left: 0; color: #999; transition: 0.2s; pointer-events: none; }
.form-group input:focus + label,
.form-group input:not(:placeholder-shown) + label {
  top: -1.2rem; font-size: 0.8rem; color: #007bff;
}
.form-group input:focus { border-color: #007bff; outline: none; }
</style>

การจัดสไตล์ Placeholder ด้วย CSS

::placeholder {           /* Standard */
  color: #999;
  opacity: 1;               /* Firefox ต้องการ opacity: 1 */
}

::-webkit-input-placeholder { /* Chrome/Edge/Safari */
  color: #999;
}

:-ms-input-placeholder {  /* IE 10-11 */
  color: #999;
}

::-moz-placeholder {      /* Firefox 19+ */
  color: #999;
  opacity: 1;
}

Placeholder ใน Textarea

<textarea placeholder="Write your message here... (max 500 chars)" 
          maxlength="500" rows="4"></textarea>

JavaScript: ตรวจสอบ Placeholder Support

if ('placeholder' in document.createElement('input')) {
  // Browser supports placeholder
} else {
  // Fallback for old browsers (IE9-)
}

สรุป: Placeholder = คำแนะนำ/ตัวอย่าง (Hint/Example), Label = ชื่อฟิลด์ (Name) - ใช้ทั้งคู่ร่วมกัน