Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> CSS

Cách xóa giá trị input khi focus (clear on focus) với CSS/JS

Giới thiệu

Xóa giá trị input khi người dùng focus (click/vào ô) là pattern cũ, hiện nay ít dùng vì gây khó khăn cho người dùng (mất dữ liệu nếu click nhầm). Thay thế tốt hơn: Placeholder hoặc Clear button (nút x) xuất hiện khi có giá trị.

Cách cũ: Inline onfocus (Không khuyến khích)

<input type="text" onfocus="this.value=''" value="Some random text...">

Nhược điểm: Xóa luôn dữ liệu hợp lệ, không thể khôi phục, vi phạm UX heuristic "User control and freedom".

Cách hiện đại: Clear Button (Nút xóa) - Khuyên dùng

<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Input Clear Button</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  <style>
    * { box-sizing: border-box; }
    body { font-family: 'Segoe UI', system-ui, sans-serif; padding: 40px 20px; background: #f5f5f5; }
    .input-wrapper { position: relative; max-width: 400px; margin: 0 auto; }
    .clearable-input {
      width: 100%;
      padding: 14px 48px 14px 16px; /* Padding-right cho nút x */
      font-size: 16px;
      border: 2px solid #e0e0e0;
      border-radius: 10px;
      background: #fff;
      transition: border-color 0.2s, box-shadow 0.2s;
    }
    .clearable-input:focus { outline: none; border-color: #667eea; box-shadow: 0 0 0 3px rgba(102,126,234,0.15); }
    .clear-btn {
      position: absolute; right: 10px; top: 50%; transform: translateY(-50%);
      width: 28px; height: 28px; border-radius: 50%;
      background: transparent; border: none; color: #aaa;
      cursor: pointer; display: flex; align-items: center; justify-content: center;
      opacity: 0; visibility: hidden; pointer-events: none;
      transition: all 0.2s;
    }
    .clearable-input:not(:placeholder-shown) + .clear-btn { opacity: 1; visibility: visible; pointer-events: auto; }
    .clear-btn:hover { background: #f0f0f0; color: #333; }
    .clear-btn:active { transform: translateY(-50%) scale(0.9); }
  </style>
</head>
<body>
  <h1 style="text-align:center; margin-bottom:30px">Clear Button Pattern</h1>
  <div class="input-wrapper">
    <input type="text" class="clearable-input" placeholder="Nhập từ khóa tìm kiếm..." value="Giá trị mẫu">
    <button type="button" class="clear-btn" aria-label="Xóa nội dung"><i class="fas fa-times"></i></button>
  </div>
  <p style="text-align:center; margin-top:20px; color:#666; font-size:14px">Nút X hiện khi có nội dung. Click để xóa, giữ nguyên nếu click nhầm.</p>
  <script>
    document.querySelectorAll('.clearable-input').forEach(input => {
      const btn = input.nextElementSibling;
      btn.addEventListener('click', () => { input.value = ''; input.focus(); input.dispatchEvent(new Event('input')); });
      input.addEventListener('input', () => {
        btn.style.opacity = input.value ? '1' : '0';
        btn.style.visibility = input.value ? 'visible' : 'hidden';
        btn.style.pointerEvents = input.value ? 'auto' : 'none';
      });
    });
  </script>
</body>
</html>

So sánh 2 cách

Tiêu chí onfocus clear Clear Button
UXTồi (mất data)Tốt (user control)
AccessibilityKémTốt (aria-label)
MobileDễ xóa nhầmDễ bấm, có target lớn
Khuyến nghịKhông dùngDùng

Placeholder - Lựa chọn đơn giản nhất

Nếu chỉ muốn gợi ý, dùng placeholder (mặc định biến mất khi focus, hiện lại khi blur rỗng):

<input type="text" placeholder="Tìm kiếm...">

CSS tùy biến màu placeholder:

input::placeholder { color: #aaa; opacity: 1; } /* Firefox cần opacity:1 */
input:focus::placeholder { color: transparent; } /* Ẩn khi focus */