'Select All' on a Streamlit Multiselect

Hi all, I’ve been trying to get a “Select All” checkbox to work on a multiselect widget by doing the following:

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

But the way the checkbox is shown before the multiselect widget is a bit counterintuitive, is there a way to have the checkbox after the mutliselect?

Hey @Venide,
First, Welcome to the Streamlit Community!!! :partying_face: :partying_face: :two_hearts: :tada: :tada: :tada:

EXCELLENT QUESTION!! I’m so glad you asked! Let us dig into all the possibilities!

Option 1: all through code
This bit of code will put the checkbox after your multiselect, but if it’s checked, the options won’t show up in the multiselect as it currently does.

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

all_options = st.checkbox("Select all options")

if all_options:
    selected_options = ['A', 'B', 'C']

selected_options # this uses MAGIC to print the options to the screen!

Option 2: unique option in the widget
This lets the user have a drop-down option in the multiselect that takes priority and is displayed in the widget itself

selected_option_2 = st.multiselect("Select one or more options:",['A', 'B', 'C', 'All'])

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

selected_option_2

Option 3: Containers (my fav)
This is my personal favourite! If you use the st.beta_container you can have the best of both worlds! a multiselect that populates with the options that the user selects and a checkbox the appears after it. This is because, with the power of containers, you can place objects and widgets out of order from how they are coded (yes you read that right! :star_struck:)

container = st.beta_container()
all = st.checkbox("Select all")
 
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'])

Here is a gif of an app where I put all these options side-by-side you you can see the differences I mean!

multiselect_all · Streamlit

Happy Streamlit-ing!
Marisa

1 Like