Is there a way to keep the focus (cursor) in a text_input when the key changes?

Hi,

I am trying to put together a simple math app and since I found no easy way to
reset the value of a text_input I came up with creating a new one with randomly hashed keys.
The callback which is called first will trigger the creation of a new text_input.
But it is loosing focus.
What I want to achieve is that the cursor always stays in the box and the result is always submitted when Return is pressed.

Any idea how this could work?
I read that a Custom Component could be used for this, but I am
not that familiar with JS…

import streamlit as st

import uuid

if 'stored_value' not in st.session_state:
    st.session_state['stored_value'] = 'x'

if 'uuid' not in st.session_state:
    st.session_state['uuid'] = uuid.uuid4()

st.text(f'st.session_state[stored_value] is "{st.session_state["stored_value"]}"')

def cbk():
    st.write('callback')
    st.session_state['stored_value'] = 'x'

if st.session_state['stored_value'] == 'x':
    st.write('create new hash')
    hash = uuid.uuid4()
    st.session_state['uuid'] = hash
else:
    st.write('use cached hash')
    hash = st.session_state['uuid']

answer = st.text_input(f'', value='', 
                            key=hash,
                            on_change=cbk)

st.session_state['stored_value']  = answer

st.text(f'answer is "{answer}"')
st.text(f'st.session_state[stored_value] is "{st.session_state["stored_value"]}"')

I created a feature request for that

Expose React .focus() and / or autoFocus on TextWidgetsMixin (e.g. TextInput, TextArea)

1 Like

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.