How do you clear the input box after hitting enter?

Summary

I am creating a todo web app, and while testing it I notice when I hit enter when there was text in the input box the text remained there!

Steps to reproduce

Code snippet:

import streamlit as st

import function

todos = function.get_todos()


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


st.title("My Todo App")
st.subheader('This is my todo app.')
st.write("The app is to increase your productivity")

for index, todo in enumerate(todos):
    checkbox = st.checkbox(todo, key=todo)
    if checkbox:
        todos.pop(index)
        function.write_todos(todos)
        del st.session_state[todo]
        st.experimental_rerun()
st.text_input(label=' ', placeholder='Add new todo...',
              on_change=add_todo, key='new_todo')


* Link to your deployed app: https://nishanth-pallela-my-todo-app-todowebapp-7h260z.streamlit.app/
Visit the link above to get to my app.
Please help me!!

Hey @Nishanth-Pallela,

Check out @mathcatsand’s awesome answer for this question here.

def add_todo():
todo = st.session_state[β€œnew_todo”] + β€˜\n’
todos.append(todo)
function.write_todos(todos)

# Clear the input box after hitting enter
st.session_state["new_todo"] = ""

##This code works by first storing the value of the input box in the session state. Then, after the user hits enter, the session state is cleared. This will cause the input box to be empty the next time the user clicks on it.

Thx so much!

2 Likes