Empty out text input upon button click

Summary

I have a text input that upon submission is rendered disabled, but retains the user input value as its placeholder. However, now I want a button that re-enables the text input. I’ve achieved this but since my conditions for running some of my code is dependent on the text input not being empty (aka != “”). And so now, when I click on the button, and the text input is re-enabled, the previous value gets rerun through my code, when in fact, I want the user to write a new input, not rerun the previous value. Hope this makes sense, I’ll attach a snippet of my code below.

Steps to reproduce

Code snippet:

import streamlit as st 

def toggle():
    st.session_state.disabled = not st.session_state.disabled
    st.session_state.prompt = ""
    # affects disabled param but not value (prompt) ???

if "disabled" not in st.session_state:
    st.session_state.disabled = False

if 'prompt' not in st.session_state:
    st.session_state.prompt = ""

if 'last_clicked' not in st.session_state:
    st.session_state.last_clicked = -1

prompt_container = st.empty()
prompt = prompt_container.text_input('initial_prompt', value=st.session_state.prompt, label_visibility="collapsed", 
                                     placeholder='write me a story about...', 
                                     on_change=toggle, disabled=st.session_state.disabled)
prompt_container = st.button("Edit prompt", on_click=toggle)

if prompt != "":
    if st.session_state.last_clicked == -1:
        # another clause that makes sure it is the initial input, last_clicked is not changed within this if block so dw abt it.
        
        ## code using prompt
        
        # WHEN I CLICK ON EDIT PROMPT, THE PROMPT RETAINS THE PREV PROMPT AND SO IT RUNS AGAIN AS IT != ""
        
        st.session_state.prompt = ""

I’ve tried using session state variables as you can see for the value of the text input but it hasn’t worked as I expected. Maybe I should be using an on_change function for the text input instead of this “if not empty” clause, but I’m already using toggle.

TL;DR: how can I somehow access prompt_container.text_input and equate it to "" without getting a bunch of errors ???

You can access and change a widget’s state in st.session_state if you add a key to the widget.

what do you mean by widget’s state exactly? could you provide an example

For a text_input() it would be:

st.text_input("Type something", key="user_input")

Then you can access or set the value in st.session_state.user_input.

def on_click():
    st.session_state.user_input = ""

st.text_input("Type something", key="user_input")
st.button("Clear", on_click=on_click)
1 Like

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