How to get the selected value of a bootstrap dropdown in code using Python & Flask?
I have accomplished more or less what you're looking for without JS by using the syntax variable = form_name.form_field.data
(in routes.py
).
I hope this helps.
Edited:
Probably best to access the form's attributes directly.Also,
forms.py:
class IndexForm(FlaskForm): car_options = SelectMultipleField( u'Select Color', choices=[('Red', 'red'), ('Blue', 'blue'), ('Green', 'green')], size=1) submit = SubmitField('Submit')
index.html:
<form action='/' , method='POST'> {{form.hidden_tag() }} <button class="btn btn-info btn-md dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" name="color_dropdown" > Select Color <span class="caret"></span> </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> {% for subfield in form.choices %} <a class="dropdown-item" href="#"> {{ subfield.label }} </a> {% endfor %} </div> <div class="submit"> {{ form.submit(class="btn btn-info") }} </div> </form>
routes.py:
@app.route("/index", methods=['GET','POST']) def index(): form = IndexForm() if form.validate_on_submit(): color_choice = form.car_options.data if color_choice = 'green': print("Sick bro") else: pass #since you can access the choices as an attribute of the form, #there is no need to define "posts" (I named it color choice) unless #you are going to use it here. return redirect('index.html') return render_template('index.html', title='My Form', form=form, data=data)