You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Flask如何获取Bootstrap下拉菜单的选中值

实现Bootstrap下拉菜单值传递到Flask的方案

问题核心

你当前使用的Bootstrap dropdown属于纯按钮组件,不是原生表单元素,无法直接将选中值随请求提交到Flask后端,需要补充表单容器、隐藏存储字段、点击监听逻辑实现值传递。


1. 修改后的HTML代码(放在home.html中)

<!-- 新增form表单包裹,提交到当前路由 -->
<form method="POST" action="/">
    <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>
    <!-- 隐藏input用于存储选中的年龄值,name属性是后端取值的对应key -->
    <input type="hidden" id="selected_age" name="selected_age" value="">
    <!-- 提交按钮,也可以根据需求改成选中后自动提交 -->
    <button type="submit" class="btn btn-primary mt-3">提交选择</button>
</form>

<!-- 补充JS监听下拉项点击事件 -->
<script>
// 监听所有下拉选项的点击动作
document.querySelectorAll('.dropdown-item').forEach(item => {
    item.addEventListener('click', function() {
        // 获取选中的年龄值
        const ageVal = this.textContent.trim()
        // 赋值给隐藏input用于提交
        document.getElementById('selected_age').value = ageVal
        // 同步更新下拉按钮的显示文本,方便用户确认选中内容
        document.getElementById('dropdownMenu3').textContent = ageVal
    })
})
</script>

如果项目已经引入了jQuery,也可以用jQuery实现上面的监听逻辑,效果完全一致。


2. 修改后的Flask代码

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

    @app.route('/', methods=['POST', 'GET'])
    def home():
        selected_age = None
        # 判断为POST请求时,获取表单提交的年龄值
        if request.method == 'POST':
            selected_age = request.form.get('selected_age')
            # 拿到selected_age后即可执行后续的业务逻辑
        # 将选中值回传到模板,可用于前端展示用户的选择结果
        return render_template("home.html", selected_age=selected_age)
     
    return app

效果验证

启动服务后选择下拉框的年龄,点击提交按钮后端即可拿到对应的年龄值,也可以在模板中通过{{ selected_age }}直接展示用户提交的结果。

内容的提问来源于stack exchange,提问作者Itamar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 21:57:02