Goyo
February 1, 2023, 11:20pm
12
It is explained in a comment to an issue linked above
opened 09:05AM - 17 Dec 21 UTC
closed 10:14AM - 22 Dec 21 UTC
type:enhancement
### Summary
Need a simpler, more effective and reliable way to clear text of … widget text_input. See example code drawn from this posted example:
https://discuss.streamlit.io/t/how-to-overwrite-the-value-user-input/7771
### Steps to reproduce
Run the example, then:
* Enter 'a'
* Enter 'b'
* Press clear button
* Enter 'c' <<< At this point the text input will be blank, as the text input is mapped to key 2 in session_state
Code snippet:
```
import streamlit as st
placeholder = st.empty()
input = placeholder.text_input('text', key=1)
click_clear = st.button('clear text input', key=3)
if click_clear:
input = placeholder.text_input('text', value='', key=2)
st.write(input)
```
### Debug info
- Streamlit version: 1.1.0
- Python version: 3.8.10
- Using Conda? PipEnv? PyEnv? Pex?
- OS version: Ubuntu 20.04 LTS
- Browser version: Chrome Version 96.0.4664.110 (Official Build) (64-bit)
### Additional information
It should be straight-forward to reliably clear text_input value. Imagine a larger form with several text_input fields, for example a search app with several search term fields (e.g. title, author, keywords). The user manipulates entries, submits the form, further manipulates entries to refine the search results. In this case, clear_on_submit is not appropriate, as they want to retain input.
Then they decide they want to start over, by clearing all text_input. Need a way to reliably clear on demand.
As a side note, it's unfortunate that binding the widget value to a session_state value does not work as expected, explained and exampled here, as it would be nice to simply clear the session state variable value which is bound to the widget.
https://discuss.streamlit.io/t/unexpected-session-state-behaviour/15216
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)