How to shift focus of input boxes automatically? #2574
-
QuestionHi All, I am trying to create an OTP input thing, where I want to imitate that behaviour where once you key in something on the first box, it automatically moves to the next box. I tried using the js code otp = [1, 2, 3, 4] # Just a sample for now
otp_set = [] # To store the individual items
i= 0
with ui.row().classes('gap-[20px] justify-center'):
for _ in otp:
i = i + 1
otp_box = ui.input(on_change=lambda i=i: gonext(i)).props('outlined dense mask="#"').classes('w-[40px]')
otp_set.append(otp_box)
otp_set[0].props('autofocus')
def gonext(i):
ui.run_javascript(f'getElement({otp_set[i].id}).focus()')
otp_set[i].props('rounded') # This one is to test if the loop works fine The loop works I tested, because the next input box is getting rounded. So my js code line is not working. Can you please advise on the correct approach here. Thanks a lot, |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi @Anindya088, This one is a bit tricky, because in case of otp_set = [ui.input(on_change=lambda i=i: focus(i+1)) for i in range(4)]
otp_set[0].props('autofocus')
def focus(i: int) -> None:
if i < len(otp_set):
ui.run_javascript(f'getElement({otp_set[i].id}).$refs.qRef.focus()') |
Beta Was this translation helpful? Give feedback.
Hi @Anindya088,
This one is a bit tricky, because in case of
ui.input
,getElement
doesn't immediately give you the HTML element to callfocus()
on. But luckily there's a workaround based on a Vue reference "qRef" we can use: