Select all checkbox that is linked to selectbox of options

Hi @Marisa_Smith !

Thanks a lot for the super useful examples above :slight_smile: Appreciate it. I am trying to take option 3 further, and synchronize the “select all” checkbox with the multiselect’s selection (same question as @Subham). My solution below requires two clicks, however. Would you know how to make it work with only one click?

if 'toggle_checkbox' not in st.session_state:
    st.session_state.toggle_checkbox = True

container = st.container()
all = st.checkbox("Select all",value = st.session_state.toggle_checkbox)

if all:
    selected_options = container.multiselect("Select one or more options:",
         ['A', 'B', 'C'],['A', 'B', 'C'])
else:
    selected_options =  container.multiselect("Select one or more options:",
        ['A', 'B', 'C'])

if ('A' in selected_options) and ('B' in selected_options) and ('C' in selected_options):
    st.session_state.toggle_checkbox = True
else:
    st.session_state.toggle_checkbox = False

Thanks in advance!

Hi @marduk,

I moved your question to its own topic to make it easier for others to search when looking for a similar answer!

You need to change your code to use the on_change call back functions. This will allow you to pre-set the st.selectbox and st.checkbox depending on the assigned values from a previous run.

Here is you code working:

# on the first run add variables to track in state
if "all_option" not in st.session_state:
    st.session_state.all_option = True
    st.session_state.selected_options = ['A', 'B', 'C']

def check_change():
# this runs BEFORE the rest of the script when a change is detected 
# from your checkbox to set selectbox
    if st.session_state.all_option:
        st.session_state.selected_options = ['A', 'B', 'C']
    else:
        st.session_state.selected_options = []
    return

def multi_change():
# this runs BEFORE the rest of the script when a change is detected
# from your selectbox to set checkbox
    if len(st.session_state.selected_options) == 3:
        st.session_state.all_option = True
    else:
        st.session_state.all_option = False
    return

selected_options = st.multiselect("Select one or more options:",
         ['A', 'B', 'C'],key="selected_options", on_change=multi_change)

all = st.checkbox("Select all", key='all_option',on_change= check_change)

Happy Streamlit-ing!
Marisa

1 Like