Created
October 25, 2025 12:31
-
-
Save Gaurav8757/388abd70a596c766a43a462b9c862a37 to your computer and use it in GitHub Desktop.
OTP NEXT-PREVIOUS CURSOR
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <div class="otp-inputs"> | |
| <input type="text" class="text-box no-arrow otp" id="otp1" maxlength="1" | |
| onkeydown="otpFocusHandler(event, 1)" autocomplete="off" /> | |
| <input type="text" class="text-box no-arrow otp" id="otp2" maxlength="1" | |
| onkeydown="otpFocusHandler(event, 2)" autocomplete="off" /> | |
| <input type="text" class="text-box no-arrow otp" id="otp3" maxlength="1" | |
| onkeydown="otpFocusHandler(event, 3)" autocomplete="off" /> | |
| <input type="text" class="text-box no-arrow otp" id="otp4" maxlength="1" | |
| onkeydown="otpFocusHandler(event, 4)" autocomplete="off" /> | |
| </div> | |
| // js code | |
| function otpFocusHandler(e, index) { | |
| const key = e.key; | |
| const current = document.getElementById("otp" + index); | |
| const next = document.getElementById("otp" + (index + 1)); | |
| const prev = document.getElementById("otp" + (index - 1)); | |
| // Allow only digits, Backspace, Delete, Tab, Arrow keys | |
| const allowedKeys = ['Backspace', 'Delete', 'ArrowLeft', 'ArrowRight', 'Tab']; | |
| if (!/^[0-9]$/.test(key) && !allowedKeys.includes(key)) { | |
| e.preventDefault(); | |
| return; | |
| } | |
| // When a digit is typed — set it and move to next box | |
| if (/^[0-9]$/.test(key)) { | |
| current.value = key; | |
| if (next) { | |
| next.focus(); | |
| } | |
| e.preventDefault(); | |
| } | |
| // Handle Backspace — move back when current is empty | |
| if (key === "Backspace") { | |
| if (current.value === "") { | |
| if (prev) { | |
| prev.focus(); | |
| prev.value = ""; | |
| } | |
| } else { | |
| current.value = ""; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment