'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 1:[1]

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.

Solution 2:[2]

Create a form with dropdown and button for submiting the form, then create js script that extract selected option and send it to the backend by HTTP POST method.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Bartosz Karwacki