Skip to content Skip to sidebar Skip to footer

Add "select-all" Option Inside A Dropdown In Dash

I want to add a 'select-all' option inside a multi-select dropdown. So, by default, there is the small 'x' on the right to clear all values and I want a similar option to get every

Solution 1:

Functionality

A bare bones implementation of a "select all" functionality for a dcc.Dropdown can be implemented with a callback like this:

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State

app = dash.Dash()

options = [
    {"label": "New York City", "value": "NYC"},
    {"label": "Montreal", "value": "MTL"},
    {"label": "San Francisco", "value": "SF"},
]

app.layout = html.Div(
    id="dropdown-container",
    children=[
        dcc.Dropdown(
            id="dropdown",
            options=options,
            value=["MTL", "NYC"],
            multi=True,
        ),
        html.Button("SELECT ALL", id="select-all", n_clicks=0),
    ],
)


@app.callback(Output("dropdown", "value"), Input("select-all", "n_clicks"))defselect_all(n_clicks):
    return [option["value"] for option in options]


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

So the idea of the code above is that every time the select-all button is clicked, we take all option values and set the value property of the dropdown to the resulting list.

Styling

Now we can use some css to make it seem like the button is inside the dropdown. In the css below I will position the button to the left of the 'x':

#dropdown-container {
  position: relative;
}

#select-all {
  height: 21px;
  position: absolute;
  top: calc(50% - 10.5px);
  right: 50px;
}

The idea here is to give the container that holds the dropdown and the button position: relative. This is so we can give position: absolute to the button and the absolute positioning of the button will be relative to dropdown-container.

For the button styles I set top to 50% minus half of the button height. This is so the button is aligned in the middle vertically like the dropdown 'x' and caret.

Post a Comment for "Add "select-all" Option Inside A Dropdown In Dash"