如何使用 Thymeleaf 获取动态输入框数据?

Posted

技术标签:

【中文标题】如何使用 Thymeleaf 获取动态输入框数据?【英文标题】:How to get dynamic input box data using Thymeleaf? 【发布时间】:2018-04-16 03:58:21 【问题描述】:

我正在使用 STS 3.9.0 Tool,我的项目基于 Spring Boot、Thymeleaf、mysqlhtml-Bootstrap 和 JQuery。

我需要获取thymeleaf中动态生成的输入框的值.. 说明

1.当点击Add Co-Owner按钮时,Jquery会被调用并生成输入框

2.我需要在@controller页面中获取动态生成的输入框值的值

JQUERY - 动态生成的输入框代码

$(document).ready(function() 
    var max_fields      = 10; //maximum input boxes allowed
    var wrapper         = $("#adding_CownerInp"); //Fields wrapper
    var add_button      = $("#addButton_Cowner"); //Add button ID
    
    var x = 0; //initlal text box count
    $(add_button).click(function(e) //on add input button click
        e.preventDefault();
        if(x < max_fields) //max input box allowed
            x++; //text box increment now x=1 after x++ x=2,so next code 2%2==0 is true
            
            
            $(wrapper).append('<div class="form-row">'			
            		+'<!-- Owner Name -->'
            		+'<div id="TextBoxDiv'+x+'" class="form-group col-md-4">'
            		+'<label for="cowner'+x+'">Name</label>'
            		+'<input id="cowner'+x+'" th:field="*listcoowner.coownername" type="text"  class="form-control" placeholder="Enter Name"></input>'
            		+'</div>'
			
            		+'<!-- Owner Phone Number -->'
            		+'<div class="form-group col-md-4">'
            		+'<label for="oph'+x+'">Phone Number</label>'
            		+'<input id="oph'+x+'" th:field="*listcoowner.cophone" type="text"  class="form-control" placeholder="+91-999-999-9999"></input>'
            		+'</div>'
			
            		+'<!-- Owner Email -->'
            		+'<div class="form-group col-md-3">'
            		+'<label for="email'+x+'">Email</label>'
            		+'<input id="email'+x+'" th:field="*listcoowner.coemail" type="email"  class="form-control" placeholder="xyz@abc.com"></input>'
            		+'</div>'
            		+'<a href="#"class="remove_field col-md-1"> X </a>'
            		+'</div>');
            
            
            
            
            
        
    );
    
    $(wrapper).on("click",".remove_field", function(e) //user click on remove text
        e.preventDefault(); $(this).parent('div').remove(); x--;
    )
);
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>Flat Addition Form</title>
<!-- Bootstrap Library CDN link -->
<link rel="stylesheet"
	href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css"
	integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M"
	crossorigin="anonymous">
	
<!-- this is for bootstrap spinner -->
<link href="../libs/jquery.bootstrap-touchspin.min.css">

</head>
<body>
<!-- Bootstrap/Jquery CDN library files -->
	<script src="https://code.jquery.com/jquery-3.0.0.js"></script>
	<script
		src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js"
		integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4"
		crossorigin="anonymous"></script>
	<script
		src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js"
		integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1"
		crossorigin="anonymous"></script>
		
	<!--External Script for add/remove input -->
	<script src="../js/AddingCoOwnerInput.js" type="text/javascript"></script>
	<!-- Panel Starts -->
	<div class="panel panel-default">
		<div class="panel-heading">
			<h3 class="panel-title">Property Addition Form</h3>
		</div>
		<div class="panel-body">
			<form action="/saveflat" th:action="@/saveflat" th:object="$flatDetails" role="form" class="form-horizontal" id="propertyreg">
				<div style="width: 900px" class="container-fluid">

					<div class="form-group">
						<label for="societyname">Society Name</label> 
						<select class="form-control" id="societyname" th:field="*entPropertyMaster">
							<option th:each="propertydetails:$propertydetails" th:value="$propertydetails" th:text="$propertydetails.propertyname"></option>
						</select>
					</div>

					<div class="form-group">
						<label for="buildinglist">Building / Wing / Block *</label> 
						<select
							class="form-control" id="buildinglist" th:field="*entPropertySub">
							<option th:each="propertydetails:$propertydetails.blockListPropSub" th:value="$propertydetails" th:text="$propertydetails.blockname"></option>
						</select>
					</div>

					<div class="form-group">
						<label for="Flat">Flat / Villa / Shop No *</label> 
						<input th:field="*flatname"
							type="text" class="form-control" id="flat" placeholder="Ex : 123..">
					</div>

				<div class="form-row">
					<!-- super buildup area -->
					<div class="form-group col-md-4">
						<label for="sbuild" class="col-form-label">Super Buildup
							Area</label> 
							<input th:field="*superbuildup" type="text" class="form-control" id="sbuild"
							placeholder="area sqft (Ex : 1200)"></input>
					</div>

					<!-- buildup area -->
					<div class="form-group col-md-4">
						<label for="build" class="col-form-label">Buildup Area</label> 
						<input th:field="*buildup"
							type="text" class="form-control" id="build"
							placeholder="area sqft (Ex : 1200)"></input>
					</div>

					<!-- carpet area -->
					<div class="form-group col-md-4">
						<label for="carpet" class="col-form-label">Carpet Area</label> 
						<input th:field="*carpetarea"
							type="text" class="form-control" id="carpet"
							placeholder="area sqft (Ex : 1200)"></input>
					</div>
				</div>
				
				<div class="form-row">
					<!-- No of bedrroms -->
					<div class="from-group col-md-6">
						<label for="bedrooms"> Number Of Bedrooms </label> 
						<input th:field="*bedrooms"
							id="bedrooms" type="text" value="" name="bedrooms" class="form-control">
					</div>

					<!-- No of bathrooms -->
					<div class="form-group col-md-6">
						<label for="bathrooms">Number Of Bathrooms</label> 
						<input th:field="*bathrooms"
							id="bathrooms" type="text" value="" name="bathrooms" class="form-control">
					</div>
				</div>
					
					<!-- Parking Number -->
			<div class="form-row">
					<div class="form-group col-md-6">
					<label for="parking">Parking</label>
					<input id="parking"  th:field="*parking" type="text" value="" class="form-control" placeholder="Ex : A1 or 123.."></input>
					</div>
					
					<div class="form-group col-md-6">
					<label for="pfloor">Parking Floor</label>
					<input id="pfloor" th:field="*parkingfloor" type="text" value="" class="form-control" placeholder="Ex : A1 or 123.."></input>
					</div>
			</div>
			
			<hr>
			
			<div class="form-row">
			<!-- Owner Name -->
			<div id="TextBoxDiv" class="form-group col-md-4">
				<label for="owner">Owner Name</label>
				<input id="owner" th:field="*ownername" type="text" value="" class="form-control" placeholder="Enter Name"></input>
			</div>
			
			<!-- Owner Phone Number -->
			<div class="form-group col-md-4">
			<label for="oph">Phone Number</label>
			<input id="oph" th:field="*ownerphone" type="text" value="" class="form-control" placeholder="+91-999-999-9999"></input>
			</div>
			
			<!-- Owner Email -->
			<div class="form-group col-md-4">
			<label for="email">Email</label>
			<input id="email" th:field="*owneremail" type="email" value="" class="form-control" placeholder="xyz@abc.com"
			 aria-describedby="emailHelp"></input>
			 <small id="emailHelp" class="form-text text-muted">We'll never share your email & Phone Number with anyone else.</small>
			</div>
			</div>
			
			<!-- co-owner -->
			
			<div id="adding_CownerInp" class="col-md-12">
			<label for="coowner" >Co-Owner</label>
			</div>
			
			<div class="form-group col-md-12">
				<input id="addButton_Cowner"  type="button" value="Add Co-Owner"  class="form-control col-md-4"></input>
			</div>
			
			<!-- submit form -->
			<div class="form-group">
			<center>
			<button type="submit" class="btn btn-primary">Save</button>
			<button type="reset"  class="btn btn-danger">Reset</button>
			</center>
			</div>


<!-- Container fluid ends -->
				</div>
			</form>
		</div>
	</div>
</body>
</html>

控制器页面代码

//To save the flat registration details
    @PostMapping("/flatreg/saveflat")
    public ResponseMsg doSaveFlatDetails(@ModelAttribute EntFlatMaster flatDetails)
    
        ResponseMsg responsemsg = new ResponseMsg();
        EntFlatMaster flatMaster = new EntFlatMaster();
        try 
            String logResponse = null;
            /*for Master*/
            if(flatDetails!=null)
            
            flatMaster = serflatDetails.doSaveFlatDetails(flatDetails);
            /*for Log*/
            if(flatMaster!=null)
            
                logResponse = doSaveLogFlatDetails(flatDetails,flatMaster.getPkflatid());
            

            /*for response message to web for master and Log both are saved checking process*/
                if(logResponse.equals("saved"))
                
                    responsemsg = new ResponseMsg("saved",flatMaster);
                
                else
                
                responsemsg = new ResponseMsg("failed",flatMaster);
                

            

         catch (Exception e) 
            // TODO: handle exception
            e.printStackTrace();
            responsemsg = new ResponseMsg("failed",flatMaster);
        
        return responsemsg;
    

请任何人帮助我..提前谢谢

【问题讨论】:

【参考方案1】:

当你使用 jQuery 插入输入时,不要使用 th: 属性!

Thymeleaf 是模板引擎。在从服务器获取视图时,每个 th: 元素都被评估为纯 HTML。这意味着在生成的视图中,没有一个元素具有th: 属性。所以你不能简单地用jQuery动态添加th:属性,因为此时它没有任何意义。

我假设你的EntFlatMaster 类有一个像List&lt;CoownerClass&gt; listcoowner 这样的字段。在这种情况下,您可以在调整输入生成代码时从动态添加的输入发送数据。在您的脚本中,您应该将th:field="*listcoowner.cophone 等属性替换为name=listcoowner[index].field。当您将add_button点击回调替换为以下代码时应该没问题:

$(add_button).click(function(e) // on add input button click
    e.preventDefault();
    if(x < max_fields) // max input box allowed

        $(wrapper).append('<div class="form-row">'
            +'<!-- Owner Name -->'
            +'<div id="TextBoxDiv'+x+'" class="form-group col-md-4">'
            +'<label for="cowner'+x+'">Name</label>'
            +'<input id="cowner'+x+'" name="listcoowner[' + x + '].coownername" type="text"  class="form-control" placeholder="Enter Name"></input>'
            +'</div>'

            +'<!-- Owner Phone Number -->'
            +'<div class="form-group col-md-4">'
            +'<label for="oph'+x+'">Phone Number</label>'
            +'<input id="oph'+x+'" name="listcoowner[' + x + '].cophone" type="text"  class="form-control" placeholder="+91-999-999-9999"></input>'
            +'</div>'

            +'<!-- Owner Email -->'
            +'<div class="form-group col-md-3">'
            +'<label for="email'+x+'">Email</label>'
            +'<input id="email'+x+'" name="listcoowner[' + x + '].coemail" type="email"  class="form-control" placeholder="xyz@abc.com"></input>'
            +'</div>'
            +'<a href="#"class="remove_field col-md-1"> X </a>'
            +'</div>');

        x++; // text box increment now x=1 after x++ x=2,so next code 2%2==0 is true
    
);

此解决方案将添加新输入并将适当的数据发送回控制器,但它也会使字段删除无效!如果您想保留字段删除,您需要为 @ 实现额外的逻辑987654332@回调,将修复索引(字段应分别从0开始索引)。

或者,您可以在 thymeleaf 和服务器端的帮助下动态实现字段。阅读this piece of documentation 了解如何操作。

【讨论】:

以上是关于如何使用 Thymeleaf 获取动态输入框数据?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用jquery生成动态输入并通过id获取值

thymeleaf中可以使用ajax动态获取数据吗

如何获取HTML中用户输入到文本框中的内容?

java如何获取输入框内容并赋值

无法使用 Spring Boot 和 Thymeleaf 以动态创建的形式获取更新的值

thymeleaf 怎么使用js获取model