(function () { const boxes = Array.from(document.querySelectorAll('.captcha')); const form = boxes[0]?.form || null; boxes.forEach((inp, i) => { inp.maxLength = 1; // Only allow A-Z0-9 (case-insensitive). Change to /^\d$/ for digits only. inp.addEventListener('beforeinput', (e) => { if (e.inputType === 'insertText' && e.data && !/^[A-Za-z0-9]$/.test(e.data)) { e.preventDefault(); } }); // Handle typing & paste inp.addEventListener('input', (e) => { let v = inp.value.toUpperCase(); // If user pasted multiple chars, spread them across the following inputs if (v.length > 1) { const chars = v.replace(/\s+/g, '').split(''); // Put first char here inp.value = chars.shift() || ''; // Fill subsequent boxes let j = i + 1; while (chars.length && j < boxes.length) { boxes[j++].value = chars.shift(); } // Focus the next empty box (or last one) const nextEmpty = boxes.find((b) => b.value === ''); (nextEmpty || boxes[boxes.length - 1]).focus(); } else { // Normal single char inp.value = v; if (v && i < boxes.length - 1) boxes[i + 1].focus(); } }); inp.addEventListener('keydown', (e) => { if (e.key === 'Backspace' && !inp.value && i > 0) { e.preventDefault(); boxes[i - 1].focus(); boxes[i - 1].value = ''; } else if (e.key === 'ArrowLeft' && i > 0) { e.preventDefault(); boxes[i - 1].focus(); } else if (e.key === 'ArrowRight' && i < boxes.length - 1) { e.preventDefault(); boxes[i + 1].focus(); } }); inp.addEventListener('focus', () => inp.select()); }); })();