Dynamic forms in Spring

I am trying to make a dynamic form using Spring forms. Basically, the form gets the name of the learning activity, and then a button appears below it, which says: "Add another learning activity." This allows the user to add another learning activity. I want him to add as much as he wants.

I have not tried this before, so obviously I ran into errors with the first solution I was thinking about. I really had the feeling that what I did would lead to an error, but just make the drive home, what I'm trying to do, here is the code:

<script language="javascript"> fields = 0; function addInput() { document.getElementById('text').innerHTML += "<form:input path='activity[fields++].activity'/><br />"; } 

 <div id="text"> <form:form commandName="course"> Learning Activity 1 <form:input path="activity[0].activity"/> <input type="button" value="add activity" onclick="addInput()"/> <br/><br/> <input type="submit"/> </form:form> <br/><br/> </div> 
+6
java javascript spring spring-mvc
source share
2 answers

You cannot use < form:input> in javascript because it is a jsp tag that runs on the server side.

However, there is nothing magical about how HTML input is bound to a field in a Spring command object; it is based only on the name. So in your javascript add a new <input type="text" name="activity[1].activity"> (for example, obviously, you are increasing the index).

Another option that I used for more complex controls is to capture the HTML of an existing control (which was created using the Spring form: input tag) and clone it, replacing the indexes with the extension number. It gets a lot easier if you use jQuery.

EDIT: One of the problems that can cause problems: you add a new input field at the end of your outer div ("text"), which means that it is not inside the form tags. This will not work.

+7
source share

Is <form:input> JSP tag? If so, then client-side Javascript to add <form:input> nodes to the DOM will not have any effect, since the server-side JSP mechanism does not interpret them.

Your Javascript should work with raw HTML and DOM, such as adding an <input> element.

+1
source share

All Articles