Create a list based on length

Summary

I want to create a form that allows me to create a form with N number_inputs based on a number chosen by the user and after that, get a list with the inputted values

I can create the form using

import streamlit as st

number = st.number_input('Choose number', step=1)
if st.button('create form'):
    with st.form('my_form'):
        for i in range(number):
            st.number_input(f'input {i}')
        st.form_submit_button('show_values')

But i don’t know how to get that values after submit the form.
Anyone can help me?

If you add keys to your inputs within the form, you can retrieve them from session_state upon submit.

import streamlit as st

if 'submit' not in st.session_state:
    st.session_state.submit = False

def submitted():
    st.session_state.submit = True

number = st.number_input('Choose number', step=1)
if st.button('create form'):
    with st.form('my_form'):
        for i in range(number):
            st.number_input(f'input {i}', key=str(i))
        st.form_submit_button('show_values', on_click = submitted)

if st.session_state.submit:
    for i in range(number):
        st.write(st.session_state[str(i)])
    st.session_state.submit = False

Note that if you have anything else on the page, the logic around the buttons can cause problems. The form will disappear if the user clicks on something outside the form and also when they click ‘show_values’. As written, you will have only one singe page load to access those form values and then they’ll be gone. Information associated to widgets is deleted when the widgets are deleted (not rendered/not executed on a particular page load). Since buttons don’t have state anything conditioned directly on a button is going to exist for a single page load then disappear. Buttons will be true for the one page load resulting from their click and go back to false as soon as the next thing happens.

1 Like