I made a simple form with an option of adding one text field dynamically on mouse click. And I will be grateful for suggestions on how I may improve the code.
@Controller
public class MyController {
public ArrayList<NewField> fieldArrayList;
@RequestMapping(value="/create", method= RequestMethod.GET)
public String myForm(Model model, @ModelAttribute NewField newField) {
fieldArrayList = new ArrayList<>();
fieldArrayList.add(newField);
model.addAttribute("dataForm", new DataForm());
return "create";
}
@RequestMapping(value="/create", method=RequestMethod.POST)
public String formSubmit(Model model, HttpServletRequest hsr, @ModelAttribute DataForm dataForm) {
if (hsr.getParameterValues("lastField") != null) {
String[] lastF = null;
lastF = hsr.getParameterValues("lastField");
List<String> d = Arrays.asList(lastF);
int count = d.size() + 1;
for (int i = 2; i < count+1; i++) {
NewField newField = new NewField();
String s1 = hsr.getParameter("p_new_" + String.valueOf(i));
String s2 = hsr.getParameter("l_" + String.valueOf(i));
newField.setStr1(s2);
newField.setStr2(s1);
fieldArrayList.add(newField);
}
}
model.addAttribute("dataForm", dataForm);
model.addAttribute("fieldArrayList", fieldArrayList);
return "view";
}
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Handing Form Submission</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
</head>
<body>
<h1>Form</h1>
<form action="#" th:action="@{/create}" th:object="${dataForm}" method="post">
<p>Id: <input type="text" th:field="*{id}" /></p>
<p>Name: <input type="text" th:field="*{content}" /></p>
<script type="text/javascript">
$(function() {
var addDiv = $('#addinput');
var i = $('#addinput p').size() + 1;
$('#addNew').live('click', function() {
$('<p><label> ' + document.getElementById('p_new').value + '</label><input type="text" name="p_new_' + i
+'" /><input type="hidden" value="' + document.getElementById('p_new').value
+ '" name="l_' + i
+ '" /><input type="hidden" value="' + i + '" name="lastField" /> </p>').appendTo(addDiv);
//alert(i);
i++;
return false;
});
$('#remNew').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
</script>
<div id="addinput">
<p>
</p>
</div>
<p><input type="submit" value="Submit" /> </p>
</form>
<input type="text" id="p_new" size="20" name="p_new" value="" placeholder="Input Value" />
<input type="button" id="addNew" value="Add New field"/>
</body>
</html>