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

时间:2017-11-03 12:07:31

标签: jquery spring-boot thymeleaf

  

我正在使用STS 3.9.0工具,我的项目基于Spring Boot,Thymeleaf,Mysql,Html-Bootstrap和JQuery。

我需要在thymeleaf中获得dynamicaly生成的输入框的值。 的说明

  

1.单击添加共同所有者按钮时,Jquery将调用它,它将生成输入框

     

2.i需要在@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 个答案:

答案 0 :(得分:1)

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

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

我认为您的EntFlatMaster班级有List<CoownerClass> 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
    }
});

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

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