When setting a dropdown menu to multi in Dash, is there a way to set a limit to how many options the user can choose? For instance “Pick three from the list below”?
This is not possible out of the box right now - you can see the list of available options at the end of the documentation here: https://plot.ly/dash/dash-core-components/dropdown.
Dropdown uses the react-select
component and it doesn’t look like this is possible in that component either: https://github.com/JedWatson/react-select.
With standard dash callbacks, you might be able to set the disabled
property of the component to True
if the len(values)
is greater than 3. I haven’t tried this.
That works, but the only issue is, say if the limit is 3, once I hit the limit, the drop down gets disabled, I won’t be able to change my selections
I don’t follow. Isn’t that what is supposed to happen if you set disabled=True
?
the entire panel gets disabled (freezes my selected items too), so if I want to, say, get rid of the last selected item, there’s no way to do so, other than refresh the page and redo the selection. well I guess I can add a button that clears selections too
Hello @sptkl
Have you been able to solve this case? I’m facing the same issue here, and cannot find any answer in this community to solve this issue.
Seems like the current limit is 5 options, however in Dash documentation(https://dash.plot.ly/interactive-graphing), you can clearly see the multiple 20+ dropdown options.
It has been more than a year since this thread.
If you can share your wisdom, I would greatly appreciate it.
Thanks.
I’ve found a workaround for this problem: a callback that sets the options of the dropdown to the choices that are currently selected if the limit is reached.
# options for the dropdown
OPTIONS = [
{"value": "value-1", "label": "Label 1"},
#...
]
@app.callback(
Output(component_id="dropdown", component_property="options"),
[
Input(component_id="dropdown", component_property="value"),
],
)
def update_dropdown_options(values):
if len(values) == 5:
return [option for option in options if OPTIONS["value"] in values]
else:
return OPTIONS
I had this exact question and came up with a simple workaround here:
That is absolutely brilliant.
This worked very well, thank you so much!
one correction:
[option for option in OPTIONS if option[“value”] in values]
I needed something similar and went with below solution, where the first chosen option is omitted everytime it exceeds 2 options:
@callback(
Output(component_id="inputs-dropdown", component_property="value"),
[
Input(component_id="inputs-dropdown", component_property="value"),
],
)
def update_dropdown_options(values):
if len(values) > 2:
return values[-2:]
else:
return values
Interesting topic. If you need to limit only maximum number of items (not exact number of items) you can set maxSelectedValues for MultiSelect from dash mantine components out of the box without additional callbacks.