"Select-All" Button for Multiselect

Hi all,

i want to create a button, that select all options of the multiselect widget similar to this 'Select All' on a Streamlit Multiselect - #2 by Marisa_Smith but with a button instead of a checkbox

Thanks for any help!

Python 3.11.0
Streamlit, version 1.28.2

Hi @DrLoeppi

You can simply replace st.checkbox with st.button and it should work.

Iโ€™ve demonstrated that in an example app here https://sandbox-examples.streamlit.app/

Hereโ€™s the code snippet:


import streamlit as st

cols = st.columns(3)

with cols[0]:
    st.header('Option 1')
    selected_options = st.multiselect("Select one or more options:",
        ['A', 'B', 'C'], key='option')
    
    all_options = st.button("Select all options")
    
    if all_options:
        selected_options = ['A', 'B', 'C']
    
    selected_options

with cols[1]:
    st.header('Option 2')
    selected_option_2 = st.multiselect("Select one or more options:",['A', 'B', 'C', 'All'], key='option_2')

    if "All" in selected_option_2:
        selected_option_2 = ['A', 'B', 'C']
    
    selected_option_2

with cols[2]:
    st.header('Option 3')
    container = st.container()
    all = st.button("Select all")
     
    if all:
        selected_options_3 = container.multiselect("Select one or more options:",
             ['A', 'B', 'C'],['A', 'B', 'C'], key='option_3')
    else:
        selected_options_3 =  container.multiselect("Select one or more options:",
            ['A', 'B', 'C'], key='option_3')

Hope this helps!

1 Like

Hi, thanks a lot for the reply!

Option 3 is what i want, only problem is, that when i want to remove one of the options after selecting all, its removes all the option. I only can access single options through the drop down menu. Is there any solution for that?

Hi,

I came up with the following solution that improves on method 3 as it does not lose all selected options when removing single ones after clicking โ€œSelect allโ€. It uses the st.session_state and a callback for the โ€œSelect allโ€ button and looks a bit hacky :slight_smile: :

import streamlit as st

st.header("Option 4")

all_options = ["A", "B", "C"]

selected_options_4 = st.multiselect(
    "Select one or more options:", all_options, key="selected_options_4"
)

def _select_all():
    st.session_state.selected_options_4 = all_options
st.button("Select all", on_click=_select_all)

selected_options_4