如何将选定的<option>元素的ID分配给另一个变量以进行进一步处理?百里香叶

时间:2018-10-30 14:18:19

标签: 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} 的帖子,该变量未绑定到任何东西(并且无法正常工作)。

我需要做的是将选定的<option>的id值绑定到表单的 $ {gusto.id} 变量,这样我的控制器便知道需要删除哪个id

因此,基本上,我需要选定的<option>的id属性(它将是Gusto类型的Object)id属性,才能在我的<form>中到达控制器。

控制器期望 int 作为ID!

3 个答案:

答案 0 :(得分:1)

答案 1 :(得分:1)

为此,您始终可以使用jquery。实际上,我相信这将是当前问题的最简单解决方案。这样,您在操作网址中将始终具有正确的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,以便更轻松地获取其价值。还有一件事,您应该在选择的开头添加一个默认选项,以使用户不会选择错误的值。

答案 2 :(得分:0)

th:onclick="'javascript:consultar();'"

<script type="text/javascript"> 
   function consultar() {

  var gustoId = $("#selectGustos option:selected").val();

    $.ajax({

        url: "/gustos/"+ gustoId + "/delete}",
        success: function(response) {

        }
    });         
}
</script>`