How to find out which input had fired?

I have two input components, one selectbox and one text-input.

The user can either select an item from the selectbox (variable ā€œoptionsā€) or input his own string into the text-input (variable ā€œsearch_stringā€).

This string will be assigned to a third variable ā€œsearch_itemā€.

However always the first (upper) input field gets used for ā€œsearch_itemā€. I want it to use the last changed input.

How can I fix it?

Hereā€™s my code:

        search_item = None
        options = st.selectbox(
            'Select a predefined thematic:',
            ('', 'Rare Earth', 'Autonomous Driving', 'Semiconductor', 'Wind Power', 'Metaverse', 'Orange Juice'),
            index=0,)
        search_string = st.text_input('Or create your own thematic search:')
        if options:
            print('options selected: ', options)
            search_item = normalize('NFKD', options.lower()).encode('ascii', 'ignore').decode('ascii').strip()
        elif search_string:
            print('search_string selected: ', search_string)
            search_item = normalize('NFKD', search_string.lower()).encode('ascii', 'ignore').decode('ascii').strip()

I could solve it by using a new session state variable.
Maybe thereā€™s an easier way?

if 'input' not in st.session_state:
            st.session_state.input = 'options'
def options_selected():
    print('options_selected()')
    st.session_state.input = 'options'
def search_string_selected():
    print('search_string_selected()')
    st.session_state.input = 'search_string'
options = st.selectbox(
    'Select a predefined thematic:',
    ('', 'Rare Earth', 'Autonomous Driving', 'Semiconductor', 'Wind Power', 'Metaverse', 'Orange Juice'),
    index=0,
    on_change=options_selected)
search_string = st.text_input(
    'Or create your own thematic search:',
    on_change=search_string_selected)
if st.session_state.input == 'options':
    print('options selected: ', options)
    search_item = normalize('NFKD', options.lower()).encode('ascii', 'ignore').decode('ascii').strip()
elif st.session_state.input == 'search_string':
    print('search_string selected: ', search_string)
    search_item = normalize('NFKD', search_string.lower()).encode('ascii', 'ignore').decode('ascii').strip()

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