Can limit the amount if values a user can input in Dash-Ploty component

Viewed 433

trying to limit the amount of inputs a user can enter in my multi-dropdown. In my code below, I have it set to 4 values MAX!

This code doesn't bring back errors, but it's not functioning like I want it to. I want the callback to stop users from entering more inputs once the number exceeds 4.

@app.callback(
    [dash.dependencies.Output("input-warning", "children"),
    dash.dependencies.Output("dynamic-dropdown", "options")],
    [dash.dependencies.Input("dynamic-dropdown", "search_value")],
    [dash.dependencies.State("dynamic-dropdown", "value")],
)
def update_multi_options(search_value, value):
    conn.rollback()
    if search_value is None:
        raise PreventUpdate
    elif len(value) >= 4:
        children = html.P("limit reached",id='input-warning')
        return [children, [o for o in OPTIONS if o["value"] in value]]  
    else:
    # Make sure that the set values are in the option list, else they will disappear
    # from the shown select list, but still part of the `value`.
        return [
            o for o in OPTIONS if search_value.upper() in o["label"].upper() or o["value"] in (value or [])
        ]

I made an elif conditional to try and limit the inputs, I couldn't get it to work however.

Would greatly appreciate some guidance on why my code doesn't achieve what I want it to.

1 Answers

You could set the disabled key value for each option to True when the max number of options has been reached so the remaining options can't be selected anymore. When you have not reached the threshold you can return your original list of options (Which are implicitly enabled).

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.Dropdown(
            id="dropdown",
            options=default_options,
            value=["MTL", "NYC"],
            multi=True,
        ),
        html.Div(id="warning"),
    ]
)


@app.callback(
    Output("dropdown", "options"),
    Output("warning", "children"),
    Input("dropdown", "value"),
)
def update_multi_options(value):
    options = default_options
    input_warning = None
    if len(value) >= 4:
        input_warning = html.P(id="warning", children="Limit reached")
        options = [
            {"label": option["label"], "value": option["value"], "disabled": True}
            for option in options
        ]
    return options, input_warning


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

dropdown-limit

Related