Prevent app refresh after form_submit_button

I am trying to create a form where the user can select certain options with checkboxes. I want to then use these choices further on in my code.
The problem is that for some reason, nothing within the “if submit_button” loop is being executed. why?

with st.form(key="source_selection"):  # Create a form
    st.write("Please choose the options you want to use.")
    for option in options:
        st.checkbox(option, key='checkbox_' + option)
    submit_button = st.form_submit_button(label="Submit")
    if submit_button:  # Check if submit button is clicked
        print('SUBMITTED')
        selected_options = [option for option in options if st.session_state['checkbox_' + option]]
        st.write("Post-submit selected options:")
        st.write(selected_options)
        if selected_options:
            # update session state with selected options
            st.session_state.app_state.selected_options = selected_options
            st.write(f"Selected Options: {', '.join(selected_options)}")
            send_selected_sources_to_backend(selected_options)
        else:
            st.warning("Please select at least one option.")

It seems like it works fine to me – here’s my attempt to make a complete script

import streamlit as st

options = ["option1", "option2", "option3", "option4", "option5"]

if "app_state" not in st.session_state:
    st.session_state.app_state = {}
    st.session_state.app_state["selected_options"] = []


def send_selected_sources_to_backend(selected_options):
    st.info(f"Sending selected options to backend: {selected_options}")


with st.form(key="source_selection"):  # Create a form
    st.write("Please choose the options you want to use.")
    for option in options:
        st.checkbox(option, key="checkbox_" + option)
    submit_button = st.form_submit_button(label="Submit")
    if submit_button:  # Check if submit button is clicked
        print("SUBMITTED")
        selected_options = [
            option for option in options if st.session_state["checkbox_" + option]
        ]
        st.write("Post-submit selected options:")
        st.write(selected_options)
        if selected_options:
            # update session state with selected options
            st.session_state.app_state["selected_options"] = selected_options
            st.write(f"Selected Options: {', '.join(selected_options)}")
            send_selected_sources_to_backend(selected_options)
        else:
            st.warning("Please select at least one option.")

st.write("selected:")
st.write(st.session_state.app_state["selected_options"])

It’s possible that it’s not working in your case because there’s something besides the code that you’ve posted is breaking something.

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