Home > Software engineering >  How to limit the number of selected checkboxes in checklist in Dash(plotly)?
How to limit the number of selected checkboxes in checklist in Dash(plotly)?

Time:11-30

My question is the same as this one that is how to limit selected number of checkboxes but I wanted this feature for the checklist in Dash provided by plotly. I have read the official documentation but can't find anything useful.

Thanks for the help in advance.

CodePudding user response:

I've answered a similar question for dropdowns here. We can use the same approach here with some adjustments.

Both the dcc.Dropdown component and the dcc.Checklist component have an options prop that allows setting whether each option is disabled or not.

We can use this by disabling all other options when your option limit has been reached.

from dash import Dash, html, dcc
from dash.dependencies import Output, Input


default_options = [
    {"label": "A", "value": "A"},
    {"label": "B", "value": "B"},
    {"label": "C", "value": "C"},
    {"label": "D", "value": "D"},
    {"label": "E", "value": "E"},
    {"label": "F", "value": "F"},
]


app = Dash(__name__)
app.layout = html.Div(
    [
        dcc.Checklist(
            id="dropdown",
            options=default_options,
        ),
    ]
)


@app.callback(
    Output("dropdown", "options"),
    Input("dropdown", "value"),
)
def update_multi_options(value):
    options = default_options
    if len(value) >= 3:
        options = [
            {
                "label": option["label"],
                "value": option["value"],
                "disabled": option["value"] not in value,
            }
            for option in options
        ]
    return options


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

The above example disables all other checkbox when 3 checkboxes have already been selected.

  • Related