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

时间:2019-03-03 09:10:31

标签: javascript html5 spring-boot arraylist thymeleaf

如何获取Selected选项的值并在相同的html中使用它,以通过百里香和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混合的更好解决方案。

1 个答案:

答案 0 :(得分:0)

您可以使用百里香叶片段和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;

}

希望这对您有用。

相关问题