Thymeleaf中如何将下拉选中项赋值给全局变量并实现计算跳转
实现方案
1. 新增隐藏输入存储选中值
在计算按钮所在的<form>里添加两个隐藏输入框,分别存储typest(用于拼接跳转路径)和选中的ssection(即第二个下拉的beamer值):
<form method="post" role="form" th:action="@{'/workspace/selectbeam/' + ${typest} + '/' + (${ssection} ?: '')}" th:object="${calbeamr}" id="calculateForm" > <!-- 新增隐藏输入 --> <input type="hidden" id="typestInput" th:value="${typest}" /> <input type="hidden" id="ssectionInput" name="ssection" th:value="${ssection ?: ''}" /> <!-- 原有输入区域 --> <div class="container"> <div class="row mt-3" th:switch="${sbeam}"> <div class="input-group" th:case="b1.png" style="width: 250px; padding: 5px;"> <label class="input-group-addon" style="padding: 5px;">P</label> <input class="form-control" id="b1" name="b1" type="text" autocomplete="off" style="padding: 5px;"> <label class="input-group-addon" style="padding: 5px">(kN)</label> <label class="input-group-addon" style="padding: 5px">L</label> <input class="form-control" id="b1l" name="b1l" type="text" autocomplete="off" style="padding: 5px;"> <label class="input-group-addon" style="padding: 5px">(m)</label> </div> </div> <button class="btn btn-secondary mb-2" type="submit">Calculate</button> </form>
2. 优化第二个下拉菜单的交互
修改第二个下拉的按钮文本,默认显示已选中的ssection(如果后端传了值),同时更新下拉选项的点击逻辑:
<div class="container"> <div class="row"> <div class="col mt-4"> <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle w-100" type="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false" id="dropdownMenu2" th:text="${ssection != null ? ssection : 'Select Steel Section'}"> Select Steel Section </button> <ul class="dropdown-menu pre-scrollable w-100" aria-labelledby="dropdownMenu2" style="overflow-y: auto; max-height: 150px;"> <li th:each="beamer : ${beamsteel}"> <button class="dropdown-item" type="button" th:value="${beamer}" th:text="${beamer}" onclick="updateSsection(this)"></button> </li> </ul> </div> </div> </div> </div>
3. 添加JavaScript处理选中逻辑
在页面底部(比如</body>前)添加JS代码,实现选中beamer后更新ssection值,并同步修改表单的跳转路径:
<script> function updateSsection(elem) { // 获取选中的beamer值 const selectedBeamer = elem.value; // 更新下拉按钮的显示文本 document.getElementById('dropdownMenu2').textContent = selectedBeamer; // 更新隐藏输入框的ssection值 document.getElementById('ssectionInput').value = selectedBeamer; // 动态修改计算表单的action路径,确保跳转时携带最新的ssection const typest = document.getElementById('typestInput').value; const form = document.getElementById('calculateForm'); form.action = `/workspace/selectbeam/${typest}/${selectedBeamer}`; } </script>
后端注意事项
- 如果后端通过路径变量接收
ssection,确保接口路径匹配/workspace/selectbeam/{typest}/{ssection} - 如果需要把
ssection作为表单参数处理,可直接通过@RequestParam("ssection")获取,无需修改表单action
内容的提问来源于stack exchange,提问作者SERKAN AYDOGDU
相关产品推荐
相关产品推荐

