2

I am using STS 3.9.0 Tool, my project based on Spring Boot, Thymeleaf, Mysql, Html-Bootstrap and JQuery.

I need to get the value of dynamicaly generated input boxes in thymeleaf.. Explanation

1.While Clicking Add Co-Owner button the Jquery will called and it will produces the input box

2.i need to get the values of the dynamically generated input box values in @controller page

JQUERY - Dynamically generated input box code

$(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="[email protected]"></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="[email protected]"
			 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>

The Controller Page Code

//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;
    }

Please any one help me..Thanks in advance

1 Answer 1

1

When you insert inputs with jQuery don't use th: attributes!

Thymeleaf is templating engine. While obtaining a view from server every th: elements are evaluated to plain HTML. That means in generated view none of element has th: attributes. So you can't simply add dynamically th: attributes with jQuery, because at this point it means nothing.

I assume that your EntFlatMaster class has a field like List<CoownerClass> listcoowner. In that case you can send data from your dynamically added inputs when you adjust you input generation code. In your script you should replace attributes like th:field="*{listcoowner.cophone} to the name=listcoowner[index].field. Should be fine when you replace add_button click callback with a following code:

$(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="[email protected]"></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
    }
});

This solution will add new inputs and send proper data back to controller, however it will also make field removal invalid! If you want to keep fields removal you'll need to implement additional logic for remove_field callback, that would fix the indexes (fields should be indexed respectively from 0).

Alternatively, you can implement dynamically fields with help of thymeleaf and server side. Read this piece of documentation to know how to do that.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.