Solution for Clearing `st.text_input` After Submission in Streamlit

Hello everyone,
as many of you, I struggled with clearing st.text_input after submission. The text persists, forcing manual deletion—a poor UX. .

After reading many answer on Clear the text in text_input, I made the following script which help achieved the expected result for better UX.

Context (My Use Case):

  • App lets users select a turbine from a dropdown or add a new one if it doesn’t exist.
  • Local deployment (future: Databricks).
  • Versions:
    • Streamlit 1.45.1
    • Python 3.12.4

Working Solution

import streamlit as st
# turbine_list : List

with st.sidebar:
    st.title("Turbine Management")
    
    # 1. Dropdown for existing turbines
    selected_turbine = st.selectbox(
        "Select Turbine",
        st.session_state.get('turbines', [""] + turbine_list)  # Default empty option
    )
    
    # 2. Form to add new turbines (auto-clears input on submit)
    with st.form("add_turbine_form", clear_on_submit=True, border=False):
        new_turbine = st.text_input("Add New Turbine", key="new_turbine")
        submitted = st.form_submit_button("Add")
        
        if submitted:
            if new_turbine:
                add_turbine(new_turbine)  # Your custom function
                st.toast(f"✅ Added turbine: {new_turbine}")  # Auto-disappears
                st.rerun()  # Refresh dropdown to show the new turbine
            else:
                st.warning("Please enter a name before adding a turbine.")

Key Improvements:

  1. clear_on_submit=True

    • Automatically clears the input field on submission.
    • No manual session state management needed.
  2. User Feedback

    • st.toast() for transient success messages (no clutter).
    • Warning message if input is empty.
  3. Dropdown Sync

    • st.rerun() ensures the selectbox updates immediately with the new turbine.
  4. Edge Cases Handled

    • Default [""] + turbine_list avoids empty dropdowns.

Why This Works

  • Forms in Streamlit (st.form) handle input states better than standalone inputs.
  • clear_on_submit is the magic parameter for resetting inputs.
  • st.toast (introduced in Streamlit 1.29+) is cleaner than st.success.

Community Note

If you’re on an older Streamlit version (<1.29), replace st.toast with:

st.success("Added!")  
time.sleep(2)  # Give users time to read  
st.empty()  # Clear the message  

I hope this will help you guys,
Happy coding !:sparkles: :rocket: :wink:

Ps: I help myself with DeepSeek to get this solution!