Clear the text in text_input

I can get the text entered by a user for streamlit.text_input.

Is there a way to empty the text that was entered? It seems that I can only set the text in text_input when I first declared it like streamlit.text_input(‘Text’, ‘My Text’).

Thanks.

2 Likes

Hi @demoacct,

Looks like we still have an open documentation issue around this! Thanks for the reminder. :smiley:

Check out the techniques discussed in the above issue thread and see if one of the ideas – e.g. using a button to reset the input – will work for you.

Thanks!

Hello, I got the same issue.

I type in a text (to be interpreted as a command) into the text_input that should be cleared after the execution, so that I can type in the next “command” without having to delete the previous one.

An additional button does not really make sense for that purpose.

2 Likes

It’s strange that this is still an issue, as it seems like such a basic need. If I have a text input:

search_query = st.sidebar.text_input("Search")

Why can’t I in my script say

search_query = ""

to reset it?

5 Likes

Just wondering, has this been solved?

2 Likes

Hello, everyone

I have one input text user filed. However, if the user writes the text in the input field after the following button, the field already exists with old text. So how shall I empty the input text filed or next time?

Looks like clearing widget values of text_input etc is still a challenge? Most workarounds I’ve seen involve “recreating” the widget with a new/alternate session state key, which is a bit ropey and not reliable.

I raised an issue here:

Has anyone been able to resolve?

For posterity and hoping to help others, a working example form with clear button and callback that clears input fields:

import streamlit as st

def clear_form():
    st.session_state["foo"] = ""
    st.session_state["bar"] = ""
    
with st.form("myform"):
    f1, f2 = st.columns([1, 1])
    with f1:
        st.text_input("Foo", key="foo")
    with f2:
        st.text_input("Bar", key="bar")
    f3, f4 = st.columns([1, 1])
    with f3:
        submit = st.form_submit_button(label="Submit")
    with f4:
        clear = st.form_submit_button(label="Clear", on_click=clear_form)

if submit:
    st.write('Submitted')

if clear:
    st.write('Cleared')
1 Like

Hi, you could use the following code instead of the above:

import streamlit as st

with st.form(“myform”, True):
f1, f2 = st.columns([1, 1])
with f1: st.text_input(“Foo”, key=“foo”)
with f2: st.text_input(“Bar”, key=“bar”)

     submitted = st.form_submit_button("Submit") 
     if submitted:
        # do whatever you want to do after the form is submitted.
1 Like

I met same problem, here is my solution:
key point is : clear_on_submit=True
same to [Shawn_Pereira]'s solution. but
I used call back for “form_submit_button” and update value using st.session_state.text += st.session_state.text_value
It’s stateful. You will learn more from Add statefulness to apps - Streamlit Docs

import streamlit as st

st.title('Input Example')
if 'text' not in st.session_state:
    st.session_state.text = ""

def update():
    st.session_state.text += st.session_state.text_value

with st.form(key='my_form',clear_on_submit=True):
    st.text_input('Enter any text', value="", key='text_value')
    submit = st.form_submit_button(label='Update', on_click=update)

st.write('text = ', st.session_state.text)

Is this issue resolved? I still cannot find a good way to do this.

It is explained in a comment to an issue linked above

The key points are:

  • You need to assign a key to the text_input.
  • You can change the widget value programatically by assigning a value to that key:
    st.session_state[key] = new_value
  • If you want to change the value in response to an user interaction (like pressing a button), do it in a callback so that the change is effective inmediately.
import streamlit as st

def clear_text():
    st.session_state["text"] = ""

input = st.text_input("text", key="text")    
st.button("clear text input", on_click=clear_text)
st.write(input)

Thanks for the response. I don’t want the button. My use case is a typical chatGPT bot, user ask a question, we produce an answer from backend and display to user. At this point, I need to clear the user input. If I remove the st.button line and just call clear_text() after some time, I get the error message
StreamlitAPIException : st.session_state.text cannot be modified after the widget with key text is instantiated.
What’s the recommendation here? Thanks
Amy

My take on that issue:

import streamlit as st

if "temp" not in st.session_state:
    st.session_state["temp"] = ""

def clear_text():
    st.session_state["temp"] = st.session_state["text"]
    st.session_state["text"] = ""

input = st.text_input("Input window", key="text", on_change=clear_text)

st.session_state["temp"]

Works quite good in https://adventure.streamlit.app/

4 Likes

With placeholder and text_input key as ‘input’, above code doesn’t work. If change key from input to text, it causes other error. Any ideas? Thank you.

 def get_text():
     input_text = st.text_input("You: ","Hello, how are you?", key=**"input"**)
     return input_text 

 def chatbot_response(prompt):
     prompt = prompt + restart_sequence
     return gpt3(prompt)
 
 placeholder = st.empty()
 user_input = get_text()

I found a not too terrible way to do it.
Consists on using a random key for the text_input widget, change it after there is a text input, and force a rerun, so the old widget is replaced with a new one.

# Runs once during app start
if "variables_setup" not in st.session_state:
    st.session_state["variables_setup"] = True
    st.session_state.input_message_key = str(random())

# message input
input_message = st.text_input(
    label = "-",
    label_visibility = "collapsed",
    key=st.session_state.input_message_key,
)

if input_message:
    st.session_state.input_message_key = str(random())
    # -- PROCESS YOUR TEXT HERE -- 
    st.experimental_rerun()

Your code works without errors for me after removing the asterisks. Of course it doesn’t clear the widget because you omitted the part of the code that takes care of that.

Hi there! I ran into this issue with one the guided assignments in this class I’m taking but the instructor didn’t address it so I found my way here and sort of cherry picked some lines from a few examples in this thread. I think it’s a pretty simple solution and I hope someone might find this helpful even though I am still a beginner. I’ll share the basic outline first, using the on_change parameter and then I’ll put all the code from the assignment in next to give it bigger context.

OUTLINE:

import streamlit as st


def clear_input_box():
    st.session_state["new_item"] = ""


st.text_input(on_change=clear_input_box,
              key="new_item")

FOR CONTEXT:

import streamlit as st
import functions

todos = functions.get_todos()

def add_todo():
    todo = st.session_state["new_todo"] + "\n"
    if todo != "\n":
        todos.append(todo)
        functions.write_todos(todos)
    st.session_state["new_todo"] = ""


st.title("My Todo App")
st.subheader("This is my to-do app")
st.write("This app is to help you stay organized")

for index, todo in enumerate(todos):
    checkbox = st.checkbox(todo, key=todo)
    if checkbox:
        todos.pop(index)
        functions.write_todos(todos)
        del st.session_state[todo]
        st.experimental_rerun()

st.text_input(label="Enter a todo", label_visibility="hidden",
              placeholder="Add a new to-do...", on_change=add_todo,
              key="new_todo")

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