How to get multiple inputs using same text_input box?

Hi, I’m designing a to-do list app in which I want to have a single text_input box which can take the tasks(one at a time) as input and create a checklist of these tasks. But when I execute the code I get only one checkbox and it gets updated every time I enter a new task (instead of having multiple checkboxes, one for each task). Is there any way to fix this?

import streamlit as st

mytsks = []

def addTask():
    tsk = st.text_input('Enter your tasks', key = 1, placeholder = 'Enter a task')
    mytsks.append(tsk)

def cmpltTask(task):
    mytsks.remove(task)


st.button('Add Task', on_click = addTask())

st.write("Your tasks:")
for task in mytsks:
    st.checkbox(task, help ='Check to mark as completed', on_change = cmpltTask(task))

Hi @Nishanth

Try the following code:

import streamlit as st
from datetime import datetime as dt

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

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

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

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


def cmpltTask(task):
    idx = st.session_state.mytsks.index(task)
    st.session_state.chkarr[idx] = not st.session_state.chkarr[idx]
    st.session_state.rerun = True

def listTasks():
    st.session_state.tskclk = []
    for i, task in enumerate(st.session_state.mytsks):
        st.session_state.tskclk.append(st.checkbox(task, value = st.session_state.chkarr[i], key = 'l' + f'{dt.now():%d%m%Y%H%M%S%f}', on_change = cmpltTask, args=(task,), help ='Check to mark as completed'))


if st.session_state.rerun == True:
    st.session_state.rerun = False
    st.experimental_rerun()

else:
    tsk = st.text_input('Enter your tasks', value="", placeholder = 'Enter a task')
    if st.button('Add Task'):
        if tsk != "":
            st.session_state.mytsks.append(tsk)
            st.session_state.chkarr.append(False)

listTasks()

Cheers

2 Likes

Thank you so much @Shawn_Pereira this was really a lifesaver!

1 Like