Sapiens
Sapiens

Reputation: 33

Drop down in Dash Python

I am building a dash app in python. I want to build an empty drop down which gets populated from a text box. So, a user enters 'abc' in the text and hits submit. The drop down value gets updated with 'abc'

Can you anyone help here?

Upvotes: 1

Views: 1397

Answers (1)

emher
emher

Reputation: 6024

Besides setting up the components, you just need a single callback that targets the dropdown options as Output with the submit button as Input and the text value along with the current drop down options as State. Here is a small example,

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

app = dash.Dash(external_stylesheets=['https://codepen.io/chriddyp/pen/bWLwgP.css'], prevent_initial_callbacks=True)
app.layout = html.Div([dcc.Input(id="input"), html.Button("submit", id="btn"), dcc.Dropdown(id="dd", options=[])])


@app.callback(Output("dd", "options"), [Input("btn", "n_clicks")], [State("input", "value"), State("dd", "options")])
def submit(n_clicks, text, options):
    return options + [{"value": text, "label": text}]


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

Upvotes: 2

Related Questions