St.form on_click callback uses old values

Hi all,
I’m having issues getting forms to work with a callback.
The code below has two input text widgets. When I click the button the code is supposed to display the values of the input text.

When I click the button once then the form clears and the default value (“”) is displayed (I have checked this with A==“” and returned True).

When I click the button a second time then the original values apprear.

This behaviour continues if I change the values and click the button, the new values are not displayed, but the most recent text -1 is returned.

def test_form():
    def sub_function(A,B):
        A
        B
    
    with st.form("my_test_form_0", clear_on_submit = True):
        textA = st.text_input('Enter text A:', value = "",placeholder = 'enter here')
        textB = st.text_input('Enter text B:', value = "",placeholder = 'enter here')
        st.form_submit_button("Submit here!", on_click=sub_function, args=(textA,textB))
    
def main():
    test_form()
    

main()    

Screenshots:

  1. Text entered, not button press

  2. Button pressed once

  3. Button pressed twice:

Please help!
Thank you.

Also please note that the same issue exists if I try to update session state:

def test_form2():
    def sub_function2():
        st.session_state['A']
        st.session_state['B']
    
    with st.form("my_test_form_0", clear_on_submit = True):
        textA = st.text_input('Enter text A2:',placeholder = 'enter here')
        textB = st.text_input('Enter text B2:',placeholder = 'enter here')
        st.session_state['A'] = textA
        st.session_state['B'] = textB
        st.form_submit_button("Submit here!", on_click=sub_function2)
        

       
def main():
    test_form2()
    

main()   

The values textA and textB are not bound until after the callback executes. Give the text_input widgets unique keys and access their values in the callback using those keys.

Thank you a million!
The code now works

def test_form():
    def sub_function():
        st.session_state.mytexta
        st.session_state.mytextb
    
    with st.form("my_test_form_0", clear_on_submit = True):
        textA = st.text_input('Enter text A:',placeholder = 'enter here', key = 'mytexta')
        textB = st.text_input('Enter text B:',placeholder = 'enter here', key = 'mytextb')
        st.form_submit_button("Submit here!", on_click=sub_function)



def main():
    test_form()
main()  
1 Like

Excellent! You’re becoming Streamliterate :slight_smile:

1 Like