java - 如何将选定的 <option> 元素的 id 分配给另一个变量以进行进一步处理? thymeleaf

标签 java spring spring-mvc thymeleaf

我正在完全编辑原始问题,因为我在这篇文章中得到了答案,它给了我一些指导:

我有这个 ThymeLeaf 模板:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <link rel="stylesheet" th:href="@{/app.css}" />
</head>
<body>
<div class="container">
    <select name="gustos" id="selectGustos">
        <option th:each="gusto : ${gustos}" th:text="${gusto.nombre}" th:value="${gusto.id}"> </option>
    </select>
    <div class="row delete">
        <div class="col s12 l8">
            <form th:action="@{'/gustos/' + ${gusto.id} + '/delete'}" method="post">
                <button type="submit" class="button">Borrar</button>
            </form>
        </div>
    </div>
</div>
</body>
</html>

<form>我正在用变量 ${gusto.id} 发表一篇文章,该变量没有绑定(bind)到任何东西(并且无法正常工作)。

我需要做的是绑定(bind)所选的<option>的 id 值传递给表单的 ${gusto.id} 变量,以便我的 Controller 知道需要删除哪个 id。

所以基本上我需要选择<option>的(它将是 Gusto 类型的对象)id 属性在我的 <form> 中旅行到我的 Controller 。

Controller 需要一个int作为id!!

最佳答案

您始终可以使用jquery来实现此目的。事实上,我相信这将是解决您当前问题的最简单的解决方案。这样,您的操作 URL 中将始终拥有正确的 id

$('#selectGustos').on('change', function() {
  var value = $(this).val();
  $('#gustosForm').attr('action', 'gustos/' + value + '/delete');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <link rel="stylesheet" th:href="@{/app.css}" />
</head>
<body>
<div class="container">
    <select name="gustos" id="selectGustos">
        <option value="-1" selected="selected">Escoger Gusto</option>
        <option th:each="gusto : ${gustos}" th:text="${gusto.nombre}" th:value="${gusto.id}"> </option>
    </select>
    <div class="row delete">
        <div class="col s12 l8">
            <form id='gustosForm' th:action="@{'/gustos/' + ${gusto.id} + '/delete'}" method="post">
                <button type="submit" class="button">Borrar</button>
            </form>
        </div>
    </div>
</div>
</body>
</html>

我在您的表单中添加了一个id,以便更容易获取它的值。还有一件事,您应该在选择的开头添加一个默认选项,以便用户不能选择错误的值。

关于java - 如何将选定的 <option> 元素的 id 分配给另一个变量以进行进一步处理? thymeleaf ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53066362/

相关文章:

java - 什么是非 Java 代码?

java - 需要有关 Java 8 流逻辑的帮助

java keystore 文件限制

java - 有什么方法可以计算java中的指令数

java - 在身份验证之前检查用户启用状态 - Spring Security

java - Spring security - 找不到类 DaoAuthenticationProvider

java - 我的 DataSource Bean 做错了什么

java - 在 spring(启动)启动时扫描使用自定义 @Annotation 注释的任意目标(TYPE、METHOD、FIELD)

java - 如何在 Spring-mvc 中使用 html 链接调用 Controller ?

java - 关闭 Spring MVC 数据绑定(bind)器