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

Tự động điền trường (Autofill) giống trường khác bằng JavaScript

Ví dụ: "Same as above" (Giống địa chỉ trên)

<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Autofill Field</title>
    <style>
        body { font-family: 'Segoe UI', sans-serif; padding: 20px; max-width: 500px; margin: 0 auto; }
        .form-group { margin-bottom: 15px; }
        label { display: block; margin-bottom: 5px; font-weight: 500; }
        input.addr { width: 100%; padding: 12px; border: 2px solid #ddd; border-radius: 6px; font-size: 16px; box-sizing: border-box; }
        input.addr:focus { border-color: #1976d2; outline: none; box-shadow: 0 0 0 3px rgba(25,118,210,0.1); }
        button { padding: 10px 20px; background: #1976d2; color: white; border: none; border-radius: 6px; cursor: pointer; font-size: 16px; }
        button:hover { background: #1565c0; }
        .hint { color: #666; font-size: 14px; margin-top: 5px; }
    </style>
</head>
<body>
    <h1>Tự động điền trường giống nhau</h1>
    
    <div class="form-group">
        <label>Địa chỉ 1 (Nhập tay)</label>
        <input type="text" class="addr" id="addr1" placeholder="Nhập địa chỉ...">
    </div>
    
    <button id="btnCopy">✅ Giống địa chỉ trên</button>
    <p class="hint">Nhấn sau khi nhập địa chỉ 1</p>
    
    <div class="form-group">
        <label>Địa chỉ 2 (Tự động điền)</label>
        <input type="text" class="addr" id="addr2" placeholder="Sẽ tự động điền..." readonly>
    </div>

    <script>
        const btnCopy = document.getElementById('btnCopy');
        const addr1 = document.getElementById('addr1');
        const addr2 = document.getElementById('addr2');

        btnCopy.addEventListener('click', () => {
            addr2.value = addr1.value;
            // Visual feedback
            btnCopy.textContent = '✅ Đã sao chép!';
            btnCopy.style.background = '#2e7d32';
            setTimeout(() => {
                btnCopy.textContent = '✅ Giống địa chỉ trên';
                btnCopy.style.background = '#1976d2';
            }, 1500);
        });

        // Bonus: Auto-copy khi nhập (real-time)
        // addr1.addEventListener('input', () => addr2.value = addr1.value);
    </script>
</body>
</html>

Mở rộng: Copy nhiều trường cùng lúc

<script>
function copyAddress(sourcePrefix, targetPrefix, fields = ['street', 'city', 'state', 'zip', 'country']) {
    fields.forEach(field => {
        const source = document.getElementById(`${sourcePrefix}${field}`);
        const target = document.getElementById(`${targetPrefix}${field}`);
        if (source && target) target.value = source.value;
    });
}

// Usage: copyAddress('billing', 'shipping');
// ID fields: billingStreet, billingCity... → shippingStreet, shippingCity...

Checkbox "Same as billing address"

<label>
    <input type="checkbox" id="sameAsBilling"> Giống địa chỉ thanh toán
</label>

<script>
const checkbox = document.getElementById('sameAsBilling');
const billingFields = ['street', 'city', 'state', 'zip'];
const shippingFields = ['street', 'city', 'state', 'zip'];

checkbox.addEventListener('change', (e) => {
    const enabled = e.target.checked;
    billingFields.forEach((field, i) => {
        const target = document.getElementById(`shipping${field.charAt(0).toUpperCase() + field.slice(1)}`);
        const source = document.getElementById(`billing${field.charAt(0).toUpperCase() + field.slice(1)}`);
        if (target && source) {
            target.value = enabled ? source.value : '';
            target.readOnly = enabled;
            target.style.background = enabled ? '#f5f5f5' : 'white';
        }
    });
});
</script>

Lưu ý UX

  • Làm readonly field đích khi auto-fill để tránh nhầm lẫn
  • Đổi màu nền field readonly (xám nhẹ) để phân biệt
  • Cho phép user uncheck để chỉnh sửa riêng
  • Validate cả 2 field khi submit