Handling Paste Events for OTP Input: A JavaScript Implementation
Certainly! The JavaScript code allows users to paste a series of digits into a One-Time Password (OTP) input form. The form has four fields for digits, and normally users enter one digit at a time. However, with this code, users can paste multiple digits at once, making the process more convenient. The code ensures that only the first four digits from the pasted data are considered. This feature enhances the user experience by offering a smoother and more efficient way to input OTPs.
<!-- HTML Form for OTP Input --> <form method="get" class="digit-group" data-group-name="digits" data-autosubmit="false" autocomplete="off" style="display: inline-flex;" id="otp_tab"> <input type="text" id="digit-1" oninput='digitValidate(this)' onpaste='handlePaste(event, 1)' tabindex="-1" onfocus="this.select();" onkeyup='tabChange(1)' name="digit-1" data-next="digit-2" class="iinp" style="caret-color: transparent;" inputmode="numeric" pattern="[0-9]" maxlength="1" autocomplete="one-time-code" /> <input type="text" id="digit-2" oninput='digitValidate(this)' tabindex="-1" onkeyup='tabChange(2)' name="digit-2" class="iinp" onfocus="this.select();" data-next="digit-3" data-previous="digit-1" style="caret-color: transparent;" inputmode="numeric" pattern="[0-9]" maxlength="1" autocomplete="one-time-code" /> <input type="text" id="digit-3" oninput='digitValidate(this)' tabindex="-1" onkeyup='tabChange(3)' name="digit-3" class="iinp" data-next="digit-4" onfocus="this.select();" data-previous="digit-2" style="caret-color: transparent;" inputmode="numeric" pattern="[0-9]" maxlength="1" autocomplete="one-time-code" /> <input type="text" id="digit-4" oninput='digitValidate(this)' tabindex="-1" onkeyup='tabChange(4)' name="digit-4" class="iinp" data-next="digit-5" data-previous="digit-3" onfocus="this.select();" style="caret-color: transparent;" inputmode="numeric" pattern="[0-9]" maxlength="1" autocomplete="one-time-code" /> </form> <script> function handlePaste(event, tabIndex) { event.preventDefault(); let pasteData = (event.originalEvent || event).clipboardData.getData('text/plain'); pasteData = pasteData.replace(/[^0-9]/g, ''); $('.digit-group input').val(''); for (let i = 0; i < pasteData.length && i < 4; i++) { let currentTabIndex = tabIndex + i; let digitInput = $('#digit-' + currentTabIndex); if (digitInput.length) { setTimeout(function() { digitInput.val(pasteData[i]).trigger('change'); if (currentTabIndex === tabIndex + 3) { digitInput.focus(); VerifyOtp(); } }, i * 50); } } } </script>
This implementation provides a practical and user-friendly interface. By allowing users to paste multiple digits at once, the code contributes to an efficient OTP verification process.