guilhermerodz / input-otp

One time passcode Input. Accessible & unstyled.
https://input-otp.rodz.dev
MIT License
2.35k stars 47 forks source link

How to change focus to the submit button after input is finished #24

Closed ahkhanjani closed 5 months ago

ahkhanjani commented 5 months ago

When you've finished typing/pasting the code, you would want to change the focus to the submit button. Right now it stays on the last slot and typing will keep rewriting it. How can we achieve this?

Thanks for the great library by the way :)

guilhermerodz commented 5 months ago

Hi @ahkhanjani. I'm glad you like the library!

If you want to focus the submit button, use JS to trigger button.focus(). However, if you want to automatically submit the form, try form.submit().

export default function Page() {
  const formRef = useRef<HTMLFormElement>(null)
  const buttonRef = useRef<HTMLButtonElement>(null)

  return (
    <form ref={formRef}>
        <OTPInput
            // ... automatically submit the form
            onComplete={() => formRef.current?.submit()}

            // ... or focus the button like as you wish
            onComplete={() => buttonRef.current?.focus()}
        />

        <button ref={buttonRef}>Submit</button>
    </form>
  )
}

Let me know if you run into any issues after that.

ahkhanjani commented 5 months ago

Thank you @guilhermerodz. Would be nice to add this to the docs.