Spring中的动态表单 [英] Dynamic Forms in Spring

查看:134
本文介绍了Spring中的动态表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Spring表单创建动态表单。基本上,表单获得学习活动的标题,然后在它下面的按钮上写着再添加一个学习活动。这使得用户可以再添加一个学习活动。我希望他能够尽可能多地添加。

I am trying to make a dynamic form using Spring forms. Basically, the form gets a title of learning activity and then there's the a button below it that says, "Add one more Learning Activity". This makes it possible for the user to add one more learning activity. I want him to be able to add as much as he likes.

我之前没有尝试过,所以很明显我遇到了我想到的第一个解决方案的错误。我真的有一种感觉做我所做的会产生错误,但只是开车回家我想做什么,这是代码:

I haven't tried this before so obviously I encountered errors with the first solution I thought of. I really had a feeling doing what I did will generate an error but just do drive home what I am trying to do, here's 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>


推荐答案

你不能使用< form:输入> 在javascript中,因为它是在服务器端运行的jsp标记。

You can't use <form:input> within the javascript because is a jsp tag that runs on the server-side.

但是,没有什么不可思议的HTML输入如何绑定到Spring命令对象中的字段;它只是基于名称。所以在你的javascript中,添加一个新的
< input type =textname =activity [1] .activity>
(例如 - 显然你会增加索引。)

However, there's nothing magical about how an HTML input gets bound to a field in the Spring command object; it's just based on the name. So in your javascript, add a new <input type="text" name="activity[1].activity"> (for example -- obviously you'll increment the index).

我用于更复杂控件的另一个选项是获取现有控件的HTML(这是使用Spring表单创建:输入标记)并克隆它,用增加的数字替换索引。如果你使用jQuery,这会变得容易多了。

Another option I've used for more complicated controls is to grab the HTML of the existing control (which was created using the Spring form:input tag) and clone it, replacing the indexes with the incremented number. This gets a lot easier if you use jQuery.

编辑添加:
一个可能导致问题的问题:你将新的输入框附加到你的外部div(text)的结尾,这意味着它不在表单标签内。那不行。

EDITED TO ADD: One issue that may cause you problems: you're appending your new input box to the end of your outer div ("text"), which means it's not inside the form tags. That won't work.

这篇关于Spring中的动态表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆