Search code examples
pythonflaskbootstrap-4dropdown

Get the dropdown selected value in bootstrap python flask


I have this dropdown that is made with bootstrap with a couple of options and I want to get the data of the selected value with flask.

HTML:

<div class="dropdown">
            <button class="btn btn-secondary dropdown-toggle text-right " type="button" id="dropdownMenu3" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                age
            </button>
            <div class="dropdown-menu pre-scrollable" aria-labelledby="dropdownMenu3">
                {% for i in range(110) %}
                    <button class="dropdown-item text-right " type="button">{{i}}</button>
                {% endfor %}
            </div>
        </div>

Python:

from flask import Flask, render_template, request
def create_app():
    app = Flask(__name__)

    @app.route('/', methods=['POST', 'GET'])
    def home():


        return render_template("home.html")
     
    return app

Solution

  • Bartosz's answer is valid, but the below code does the same without using Javascript

    html

    <form method="POST" action="{{ url_for('test') }}">
    <div class="dropdown">
                <button class="btn btn-secondary dropdown-toggle text-right " type="button" id="dropdownMenu3" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                    age
                </button>
                <div class="dropdown-menu pre-scrollable" aria-labelledby="dropdownMenu3">
                    {% for i in range(110) %}
                        <button name = "age" value = {{i}} class="dropdown-item text-right " type="submit">{{i}}</button>
                    {% endfor %}
                </div>
            </div>
        </form>
    

    app.py

    @app.route('/test', methods=['POST', 'GET'])
    def test():
        if request.method == 'POST':
            print(request.form.get('age'))
        return render_template("test.html")
    

    you need wrap the dropdown div in Form and specify its action.