How to create a delete button for removing an element from the page?

I want to create an “Add Row” button that, when clicked, will display a text input field and a “Remove Row” button. When the “Remove Row” button is clicked, the input field and the button itself will be removed from the page.

counter = st.session_state.get(‘counter’, 0)
but = st.button(“Добавить строку”)
if but:
counter += 1
st.session_state[‘counter’] = counter

text_entries = []

for i in range(counter):
    text_entries.append(st.text_input(f"string{i + 1}"))
    delete = st.button(f"delete string{i + 1}")

Hi there!
I believe you are looking for something like this:

import streamlit as st

if 'counter' not in st.session_state:
    st.session_state['counter']=0 

button_grid = st.columns(2)
with button_grid[0]:
    if st.button('Add row'):
        st.session_state['counter']+=1
with button_grid[1]:
    if st.button('Remove row'):
        st.session_state['counter']-=1

number_inputs = st.session_state['counter']

grid=st.columns(2)
with grid[0]:
    input_values = [st.text_input(f'Input field '+str(i),  key=f"text_input_{i}")
            for i in range(number_inputs)]
with grid[1]:
    input_values1 = [st.text_input(f'Input field 2',  key=f"amt1{i}")
            for i in range(number_inputs)]

This will create an add row and a remove row button.

When I had this problem, I used a number input to decide the number of rows:

import streamlit as st

number_inputs = st.number_input('number of input fields',min_value=1, max_value=10)
grid=st.columns(2)
with grid[0]:
    input_values = [st.text_input(f'Input field '+str(i),  key=f"text_input_{i}")
            for i in range(number_inputs)]
with grid[1]:
    input_values1 = [st.text_input(f'Input field 2',  key=f"amt1{i}")
            for i in range(number_inputs)]

This allows the user to directly specify the number of input fields.

Cheers,
Moiz

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