I have three chained selectors: dropdown → checklist#1 → checklist#2. Selecting an item on the dropdown menu causes checklist #1 to populate. Checking an item on checklist #1 causes checklist #2 to populate.
My question: How do I write my code so that a checkbox that has been checked on checklist #2 is automatically unchecked if the associated parent checkbox on checklist #1 is unchecked?
e.g.:
- I select Item #1 on dropdown menu. Checklist #1 populates with “Subitem #1a,” “Subitem #1b,” and “Subitem #1c.”
- I select Subitem #1a in Checklist #1-> Checklist #2 populates with [1a, 2a, 3a]
- I select Subitem #1c in Checklist #1-> Checklist #2 becomes [1a, 2a, 3a, 1c, 2c, 3c]
- I select 1a and 3c in Checklist #2.
- I uncheck Subitem #1a in Checklist #1 → I want ‘1a’ in Checklist #2 to also automatically be unselected.
The result in (5) is what I am having trouble with. I can get the options to disappear if I uncheck the parent item, but I cannot figure out how to also automatically clear the value when I uncheck the parent item.
See below code for reproduceable example (using School District (dropdown) - > Schools (checklist #1) → Grades (checklist #2). I want to prevent grades from being displayed (on a graph) if none of the checked schools (in checklist #1) actually have those grades.
Hope this makes sense.
from dash import Dash, dcc, html, Input, Output
external_stylesheets = ["https://codepen.io/chriddyp/pen/bWLwgP.css"]
app = Dash(__name__, external_stylesheets=external_stylesheets)
dropdown_items = {
'School District #1': ['School #1A', 'School #1B', 'School #1C'],
'School District #2': ['School #2A', 'School #2B', 'School #2C'],
'School District #3': ['School #3A', 'School #3B', 'School #3C']
}
app.layout = html.Div(
[
dcc.Dropdown(
id='main-dropdown',
multi = False,
options = [{'label': k, 'value': k} for k in dropdown_items.keys()],
value = 'School District #1',
),
dcc.Checklist(id="select-checklist", inline=True),
dcc.Checklist(id="grades-checklist", inline=True)
],
style={'width': '50%'}
)
# Populate School Checklist from Dropdown
@app.callback(
Output('select-checklist', 'options'),
Input('main-dropdown', 'value')
)
def set_select_checklist(dropdown_value):
return [{'label': i, 'value': i} for i in dropdown_items[dropdown_value]]
# Populate Grades Checklist from School Checklist
@app.callback(
Output("grades-checklist", "options"),
Input("select-checklist", "value"),
prevent_initial_call=True,
)
def display(select):
grade_range = []
if select:
if any('School #1' in string for string in select):
grade_range.append(3)
if any('School #2' in string for string in select):
grade_range.append(6)
if any('School #3' in string for string in select):
grade_range.append(9)
grade_range = list(range(min(grade_range)-2,max(grade_range)+1))
options = [str(x) for x in grade_range]
else:
options=[]
return options
if __name__ == "__main__":
app.run_server(debug=True)