Facebook Pixel

How do you fix focus going beyond the last OTP input in JavaScript?

Add a boundary check before focusing the next input: if (value && index < inputs.length - 1) inputs[index + 1].focus(). The condition index < inputs.length - 1 prevents focusing beyond the last input.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in OTP Input Common Bugs and Fixes

Because you are not checking if the current input is empty before focusing the previous. The fix: if (e.key === 'Backspace' && !e.target.value && index > 0) inputs[index - 1].focus(). Only go back when the current input is already empty.

Because you are not calling e.preventDefault(). The browser does the default paste, which fills only the current input (and truncates to maxlength=1). Call e.preventDefault() and manually distribute the pasted text across the inputs.

Because you are not filtering non-numeric characters. Add e.target.value = e.target.value.replace(/\D/g, '') on the input event. This removes all non-digit characters.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.