繁体   English   中英

根据从下拉列表中选择的选项填充表格

[英]populate table based on option selected from dropdown

如何获取 Selected 选项的值并在同一个 html 中使用它来使用 thymeleaf 和 spring-boot 从数据库中获取数据。

这是我的代码..

<form class="form-horizontal" action="#" method="post" data-th-action="@{/raw-stock-entry.html}" th:object="${itemReturn}">
<div class="box-body">
    <div class="form-group col-md-6">
        <label for="itemId" class="col-sm-5 control-label">Item Name <span style="color:red">*</span> </label>
        <div class="col-sm-6">
            <select class="form-control" th:field="*{itemId}" onchange="fetchData()">
                <option th:value="0">Select One</option>
                <option th:each="readyItem : ${readyItemsOnly}" 
                        th:text="${readyItem.itemName}" th:value="${readyItem.itemId}">
                </option>
            </select>
        </div>
    </div>
    <table id="Table" width="100%" >
        <thead>
           <tr>
               <th>SL#</th>
               <th>Item Name</th>
           </tr>
        </thead>
        <tbody>
           <tr th:each="itemList, itrItem : ${itemDetails}" th:if="${itemList.itemId} == 2">
                <td th:text="${itrItem.index+1}">Index </td>
                <td th:id="item" th:text="${itemList.itemName}" th:value="${itemList.itemName}"> </td>
                <td th:id="remainingQuantity" th:text="${itemList.remainingQuantity}" th:value="${itemList.remainingQuantity}"></td> 
           </tr>
        </tbody>
    </table>
</div>

在我的表中,我从我的数据库中获取项目详细信息,如果我分配了一个 itemId 值,那么只会显示该项目详细信息。 那很好。

但实际上我想显示从顶部下拉选项中选择的项目详细信息。 我可以使用 js 获取所选选项的值,但是我将如何在“th:if”字段中使用该值,以便仅显示该项目的详细信息。 在不使用 js 或使用 js+thymeleaf mix 的情况下,是否有更好的解决方案。

您可以通过使用 thymeleaf 片段和 ajax 来实现这一点。

在您的 html 中添加以下代码。

 $('.drop-down').on('change', function() { var name = $('.drop-down option:selected').val(); $.ajax({ type: 'get', url: /*[[ @{'/url'} ]]*/, data: {name:name}, success: function(returnedData){ console.log(returnedData); $('.details').html(returnedData); }, error: function(xhr, exception) { console.log(xhr); alert("error"); } }); });
 <select class="form-control drop-down" th:field="*{itemId}" > ..... </select> <div class="details"> <div th:fragment="details"> <table> ...... ...... <table> <div> <div>

并在您的控制器中编写如下代码。

@GetMapping("/url")
public ModelAndView getDetails(@RequestParam("name")String name){
   ModelAndView mv = new ModelAndView("htmlpagename::details");
   List<Item> itemDetails= repository.findByName(name);// your query result 
    mv.addObject("itemDetails",itemDetails);
     return mv;

}

希望这对你有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM