Text input default value does not work when filled by button click

Summary

Hi, can someone help me to understand the following behaviour. I know I can solve this with session state (as commented out in the example below) but I really like to understand whats going on.

As soon as you click on the autofill button the input field is correctly filled.
But if you submit the form (even if you change the text manually again after the autofill) the value is gone.

I read the button doc Button behavior and examples - Streamlit Docs
and understand the concept of reruns.

Seems I am just missing a little detail of knowledge in here :wink:

Thxalot

Steps to reproduce

Code snippet:

import streamlit as st

if st.button("Autofill"):
    autofill_value = "autovalue"
    # if know this would work: st.session_state['text'] = autofill_value
else:
    autofill_value = ""

with st.form(key="test"):

    text = st.text_input("Enter text", value=autofill_value, key="text")
    st.text(f"filled value: {text}")
    
    if st.form_submit_button("Submit"):
        st.text(f"issue with non filled value: {text}")

If applicable, please provide the steps we should take to reproduce the error or specified behavior.

Expected behavior:

Use the default value of the variable set by the button click (as it is correctly shown in the input box)

Actual behavior:

Value is empty instead of using the correctly shown value in the input box.

Debug info

Hi @naciron

Yes, the use of any widget interaction (via a button click) will cause the app to re-run. And in order to prevent that you’ll need to use Session state. Alternatively, you can also use callbacks (define a function for assigning the autofill value and use on_click parameter of st.button() to trigger the callback function to run) for adding the autofill value as well.

More details here: Add statefulness to apps - Streamlit Docs

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