DASH select/unselect checklist options

I am trying to create a button that selects/unselects all my checklist options in DASH. With the code that I have now, it is only selecting all options, the deselect option is not working.

dcc.Checklist(id='country_checklist',
                      options=[{'label': str(c), 'value': c} for c in sorted(df['Country'].unique())],
                      value=[],
                      labelStyle={'display': 'block'},
                      inputStyle={"margin-right": "5px"}
                      ),
        html.Button(className='button btn btn-primary btn-sm',
                    id='all-or-none1',
                    n_clicks=0,
                    children="Select/Unselect All")

@app.callback(Output('country_checklist', 'value'),
              [Input('all-or-none1', 'n_clicks')],
              [State('country_checklist', 'options')])

def select_all_none(all_selected, options):
    all_or_none1 = []
    all_or_none1 = [option['value'] for option in options if all_selected]
    return all_or_none1

Hi @GabrielBKaram

Your input “n_clicks” is a number that start with "0"
I think you need to add an “if” condition to return different “options” if this number is odd or even.

I tried:

def select_all_none(all_selected, options, n_clicks):
    if n_clicks % 2 == 0:
        all_or_none1 = []
        return all_or_none1

    elif n_clicks % 2 != 0:
        all_or_none1 = [option['value'] for option in options if all_selected]
        return all_or_none1

And it did not work still

This code works for me :grinning:

import dash
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output, State
import json
import dash_core_components as dcc
import dash_html_components as html
from dash.dash import no_update


app = dash.Dash(
    external_stylesheets=[dbc.themes.BOOTSTRAP]
)

app.layout = html.Div([
    dcc.Checklist(id='country_checklist',
                  options=[{'label': "Argentina", 'value': "Arg"}, {'label': "USA", 'value': "USA"}, {'label': "Rest of Word", 'value': "RoW"}],
                  value=[],
                  labelStyle={'display': 'block'},
                  inputStyle={"margin-right": "5px"}
                  ),
    html.Button(className='button btn btn-primary btn-sm',
                id='all-or-none1',
                n_clicks=0,
                children="Select/Unselect All")
])

@app.callback(Output('country_checklist', 'value'),
              [Input('all-or-none1', 'n_clicks')],
              [State('country_checklist', 'options')])
def select_all_none(all_selected, options):
    if all_selected % 2 == 0:
        all_or_none1 = []
        return all_or_none1
    else:
        all_or_none1 = [option['value'] for option in options if all_selected]
        return all_or_none1


if __name__ == "__main__":
    app.run_server(debug=True)

it worked, thanks a lot !

1 Like