Hello guys is it possible to have multiple forms on single jsp and also with a single button?
Here is my jsp page where i hava two forms, i know this way it is, it only save the second form.
<html>
<head>
<title>Update General Info</title>
<script type="text/javascript">
function validateForm()
{
var name=document.getElementById("name").value;
var surname=document.getElementById("surname").value;
var email=document.getElementById("email").value;
var amka=document.getElementById("amka").value;
if (name.length == 0)
{
alert("Name must be filled out");
return false;
} else if(surname.length == 0){
alert("Surname must be filled out");
return false;
}else if(email.length == 0){
alert("Email must be filled out");
return false;
}else if(amka.length == 0){
alert("Amka must be filled out");
return false;
}
}
</script>
</head>
<body>
<h1>Update General Info</h1>
<c:if test="${!empty user}">
<c:url var="saveArticleUrl" value="/articles/updateGeneralSave.html" />
<form:form onsubmit="return validateForm()" modelAttribute="user" method="POST" >
<table bgcolor="DBEADC" border=1>
<tr>
<th>Id</th>
<th>Team</th>
<th>Name</th>
<th>Surname</th>
<th>Username</th>
<th>Password</th>
<th>Email</th>
<th>AMKA</th>
<th>Status</th>
<th>Department</th>
</tr>
<tr>
<td><form:input readonly="true" path="id" value="${user.id}"></form:input></td>
<td><form:input readonly="true" path="team" value="${user.team}"></form:input></td>
<td><form:input id="name" path="name" value="${user.name}"></form:input></td>
<td><form:input id="surname" path="surname" value="${user.surname}"></form:input></td>
<td><form:input readonly="true" path="username" value="${user.username}"></form:input></td>
<td><form:input type="password" readonly="true" path="password" value="${user.password}"></form:input></td>
<td><form:input id="email" path="email" value="${user.email}"></form:input></td>
<td><form:input id="amka" path="amka" value="${user.amka}"></form:input></td>
<td><form:input id="status" path="status" value="${user.status}"></form:input></td>
<td><form:select path="department">
<c:forEach items="${departments}" var="dep">
<c:if test="${dep.dep_name==user.department }">
<OPTION selected VALUE="${dep.dep_name}"><c:out value="${dep.dep_name}"/></OPTION>
</c:if>
<c:if test="${dep.dep_name!=user.department }">
<OPTION VALUE="${dep.dep_name}"><c:out value="${dep.dep_name}"/></OPTION>
</c:if>
</c:forEach>
</form:select></td>
</tr>
</table>
</form:form>
</c:if>
<c:if test="${!empty phones}">
<c:url var="saveArticleUrl" value="/articles/updatePhoneSave.html" />
<form:form onsubmit="return validateForm()" modelAttribute="updatePh" method="POST" action="${saveArticleUrl}">
<table bgcolor="DBEADC" border=1>
<tr>
<th>Id</th>
<th>Phone</th>
<th>Mobile</th>
<th>Fax</th>
</tr>
<tr>
<td><form:input readonly="true" path="id" value="${phones.id}"></form:input></td>
<td><form:input id="phone" path="phone" value="${phones.phone}"></form:input></td>
<td><form:input id="mobile" path="mobile" value="${phones.mobile}"></form:input></td>
<td><form:input path="fax" value="${phones.fax}"></form:input></td>
</tr>
</table>
<input type="submit" value="Update" />
</form:form>
</c:if>
</body>
</html>
and the controllers
RequestMapping(value = "updateGeneral" , method = RequestMethod.GET)
public ModelAndView updateGeneral(#ModelAttribute("user") Users user ,#ModelAttribute("updatePh") Phone updatePh, #RequestParam("id")Integer id){
Map<String, Object> model = new HashMap<String, Object>();
model.put("user", articleService.getUser(id));
model.put("departments", articleService.listDepartments());
//twra mpike
model.put("phones", articleService.getPhones(id));
return new ModelAndView("updategeneral",model);
}
//evala akoma ena modelattri
#RequestMapping(value = "updateGeneralSave" , method = RequestMethod.POST)
public ModelAndView updateGeneralSave(#ModelAttribute("user") Users user){
articleService.updateUser(user);
return new ModelAndView("redirect:/articles/listusers.html");
}
#RequestMapping(value = "updatePhoneSave" , method = RequestMethod.POST)
public ModelAndView updatePhonesave(#ModelAttribute("updatePh") Phone updatePh){
articleService.updatePhone(updatePh);
return new ModelAndView("redirect:/articles/listusers.html");
}
You can have multiple forms in a JSP, but you can NOT send both at the same time.
You should mix both forms and both actions, retrieve all information in the action/controller and save phone and user information. Another options would be to use Ajax to send one of the form and send the other as usually.
By the way, your problem has nothing to do with Spring.
yes of courses, you can make your button to submit both your forms. But you have do it with ajax.
You need to loop through the forms on the webpage using document.forms[i] and with each form individually call the submit
Your only option is doing for ajax, you have to realize that if you Controller method will render a page after the first submit your second submit doing by HTTP will never take effect.
function submitForm(form, index){
$.ajax({
dataType: "json",
method: "POST",
url: "your controller url",
data:$('#form').serialize(),
success: function (data) {
if(index > 0){
submitForm(form+=1, index--)
}
}
});
}
You can do following trick like
Instead of sumbit button have only normal button as
<input type="button" value="Update" onClick="submit2forms();"/>
and on click of this button call below javascript method as
<script language="javascript">
function submit2forms() {
document.getElementById("form1").submit();
document.getElementById("form2").submit();
}
</script>
Related
I'm learning java and I'm practicing with thymeleaf. I made an little app where I have a list of persons (arraylist). I can add a person through a form but also edit a person from the list to update the person's firstname, lastname or birthdate through a form. Here is my problem I want when I edit a person to have its default values(firstname, lastname, bithdate) on the update form so that we can then change only the fields of interest. I have this code:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>Update Person</title>
<link rel="stylesheet" type="text/css" th:href="#{/css/style.css}"/>
</head>
<body>
<h1>Update a Person:</h1>
<!-- some tests I made to test if the value appears in the field -->
<!-- <input type="text" name="id" th:value="${person.id}" /> -->
<!-- <input type = "text" name = "firstName" th:value = "${person.firstName}" /> -->
<!-- <input type = "text" name = "sometext" th:value = "hello world" /> -->
<form th:action="#{/updatePerson/{id}(id=${person.id})}"
th:object="${person}" method="POST">
First Name:
<input type="text" th:field="*{firstName}"/>
<br/>
Last Name:
<input type="text" th:field="*{lastName}" />
<br/>
Date of Birth (DD/MM/YYYY):
<input type="date" th:field="*{birthDate}" />
<br/>
ID:
<input type="text" th:field="*{id}" />
<br/>
<input type="submit" value="Update" />
</form>
<br/>
<!-- Check if errorMessage is not null and not empty -->
<div th:if="${errorMessage}" th:utext="${errorMessage}"
style="color:red;font-style:italic;">
...
</div>
</body>
</html>
None of my default values appears in the fields except for the id. Whether I use th:field="{id}" or name="id" th:value="${person.id}". Both synthax work but the others (ie: th:field="{firstName}" or name = "firstName" th:value = "${person.firstName}" same goes for lastname and birthdate), nothing works. I even tried th:value = "hello world" (commented in the above code), it does appear! So why my person firstname, lastname, bithdate don't appear? What is wrong? My person.list html works though:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>Person List</title>
<link rel="stylesheet" type="text/css" th:href="#{/css/style.css}"/>
</head>
<body>
<h1>Person List</h1>
Add Person
<br/><br/>
<div>
<table border="1">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Date of Birth</th>
<th>Edit</th>
<th>Delete Name</th>
</tr>
<tr th:each ="person : ${list}">
<td th:utext="${person.firstName}">...</td>
<td th:utext="${person.lastName}">...</td>
<td th:text="${#temporals.format(person.birthDate,'dd-MM-yyyy')}">...</td>
<td><a th:href="#{/updatePerson/{id}(id=${person.id})}">
<span>
<img src="https://img.icons8.com/clouds/40/000000/edit.png">
</span>
</a></td>
<td>
<form th:action="#{/deletePerson}" th:method="POST">
<input type = "hidden" name = "firstName" th:value = "${person.firstName}" />
<input type = "hidden" name = "lastName" th:value = "${person.lastName}" />
<input type = "hidden" name = "id" th:value = "${person.id}" />
<input type = "hidden" name = "birthDate" th:value = "${person.birthDate}" />
<button type = "submit" >
<span>
<img src="https://img.icons8.com/metro/26/000000/delete.png" />
</span>
</button>
</form>
</td>
</tr>
</table>
</div>
<div>
<form th:action="#{/changeDao}" th:method="POST">
<select name="daoChoice">
<option th:value="none" disabled>Choisissez votre Dao</option>
<option id="jdbc" th:value="JDBC">Jdbc</option>
<option id="memory" th:value="MEMORY" th:selected="${isMemory}">Memory</option>
</select>
<button type="submit">Valider</button>
</form>
</div>
<div>
<form th:action="#{/excelLoad}" th:method="GET">
<button type="submit">Local Load</button>
</form>
</div>
<div>
<form th:action="#{/UploadFile}" method="POST" enctype="multipart/form-data">
<table>
<tr>
<td><label>Upload and Add to the table</label></td>
<td><input type="file" th:value = "file" th:name="file" /></td>
</tr>
<tr>
<td><input type="submit" value="Upload" /></td>
</tr>
</table>
</form>
</div>
<div>
<form th:action="#{/exportToExcel}" th:method="POST">
<button type="submit">Export to Excel</button>
</form>
</div>
</body>
</html>
Above my personList.html, person's firstName lastName and birthdate is printed correctly with this code:
<tr th:each ="person : ${list}">
<td th:utext="${person.firstName}">...</td>
<td th:utext="${person.lastName}">...</td>
<td th:text="${#temporals.format(person.birthDate,'dd-MM-yyyy')}">...</td>
but why in my update form this is not working ?
I'm a newbie in java programming and also in thymeleaf (also newbie), so I'd really appreciate some explanations along some tips! thanks a lot!
I found it with another post where there was a simple explanation about the key/value pair in modelAddAttribute:
You can access variables value by ${key}.
Example
model.addAttribute("key", value);
Understanding that I found my mistake in my controller:
#RequestMapping(value = { "/updatePerson/{id}" }, method = RequestMethod.GET)
public String showUpdatePersonPage(#PathVariable("id") int id, Person person, Model model) {
person = personDao.findPerson(id);
model.addAttribute("person", person);
return "updatePerson";
}
Before it was:
#RequestMapping(value = { "/updatePerson/{id}" }, method = RequestMethod.GET)
public String showUpdatePersonPage(#PathVariable("id") int id, Person person, Model model) {
person = personDao.findPerson(id);
model.addAttribute("personToModify", person);
return "updatePerson";
}
And in my html the code was:
<form th:action="#{/updatePerson/{id}(id=${person.id})}"
th:object="${person}" method="POST">
First Name:
<input type="text" th:field="*{firstName}"/>
<br/>
Last Name:
<input type="text" th:field="*{lastName}" />
<br/>
Date of Birth (DD/MM/YYYY):
<input type="date" th:field="*{birthDate}" />
<br/>
ID:
<input type="text" th:field="*{id}" />
<br/>
<input type="submit" value="Update" />
</form>
So that was because the key name used "personToModify" couldn't be found in the html as the object name used wasn't properly named:
th:object="${person}"
I can't see your Person class or controller but, for example, keeping it clean, you can create PersonForm class which can look like (might need to change Date)
import java.util.Date;
public class PersonForm {
private String firstName;
private String lastName;
private Date birthDate;
public PersonForm() {
}
public PersonForm(Person person) {
this.firstName = person.getFirstName();
this.lastName = person.getLastName();
this.birthDate = person.getBirthDate();
}
As you can see, it has fields which needs to populated and you set them in constructor, you can also apply validation annotations here if needed.
In your controller you would need to retrieve Person and using it, create and add PersonForm as model attribute. i.e.
#GetMapping("/person/edit/{id}") // you might not use id, might be username
public String editPerson(#PathVariable Long id, Model model) {
Person person = personRepository.getOne(id); // or service
PersonForm personForm = new PersonForm(person);
model.addAttribute("personForm", personForm);
// other stuff
// return html
}
and then change th:object="${person}" to th:object="${personForm}"
Now all th:field="*{firstName}" and others should be populated.
I wanted that when I change my selection in my checkbox the only selected checkbox will be selected and the previous selected checkbox will be uncheck.
My code is working but i really wanted to select only one checkbox.
In my view.
<center><table></center>
<tr>
<th><center>
List of Names</center></th>
<th colspan="3">
Actions
</th></tr>
<tr ng-repeat="role in roles">
<td>
<label>
<ion-checkbox ng-model="isChecked" ng-
change="format(isChecked,role,$index)"
ng-init="isChecked=false"><div class="wew">
{{role}}
</div></ion-checkbox>
</label>
</td>
<td>
<button ng-hide="!isChecked" ng-click="present()">P </button> </td>
<td>
<button ng-hide="!isChecked" ng-click="late()">L</button></td>
<td><button ng-hide="!isChecked" ng-click="absentss()">A</button></td>
<td><button ng-hide="!isChecked" ng-click="delete()">D</button></td>
</tr> </table>
And I think in my controller is the part where i need to change my codes to achieved the correct result.
$scope.isChecked = false;
$scope.selected = [];
$scope.format = function (isChecked, role, index) {
if (isChecked==true) {
$scope.selected.push(role);
}
else {
var _index = $scope.selected.indexOf(role);
$scope.selected.splice(_index, 1);
}
var students = $scope.selected;
console.log(students);
for( var s=0; s<students.length; s++) {
$scope.stud = [
students[s]
]
};
Thank you in advanced! I hope that someone can help in this matter.
Checkboxes are for multiple selections within a group.
Use radio buttons instead.
Example With AngularJs
This is way you can also implement.
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
angular.module('app', []).controller('appc', ['$scope',
function($scope) {
$scope.selected = 'other'; //default selection
}
]);
</script>
</head>
<body ng-app="app" ng-controller="appc">
<label>SELECTED: {{selected}}</label>
<div>
<input type="checkbox" ng-checked="selected=='male'" ng-true-value="'male'" ng-model="selected">Male
<br>
<input type="checkbox" ng-checked="selected=='female'" ng-true-value="'female'" ng-model="selected">Female
<br>
<input type="checkbox" ng-checked="selected=='other'" ng-true-value="'other'" ng-model="selected">Other
</div>
</body>
</html>
<script type="text/javascript" src="${pageContext.request.contextPath}/resources/js/jquery.validate.min.js"></script>
<script>
function setHiddenVal(){
var goAhead = true;
var myVal="I am hidden value";
document.getElementById("secretValue").value = myVal;
if (goAhead == true) {
document.forms["register-form"].submit();
}
}
</script>
</head>
<body>
<!--Main Container Starts here-->
<div class="main_container">
<div class="header">
<div class="right_panel">
<h2 align="center"><u>User Master</u></h2>
<div class="top-form">
<div>
**<form:form action="/usermaster" modelAttribute="CustomerForm" id="register-form" method="POST">**
<table cellspacing="0" cellpadding="0" border="" class="form1">
<tr>
<td class="label">Name:</td>
<td>
<form:input path="firstname"/>
</td>
</tr>
<tr>
<td class="label">Password:</td>
<td>
<form:input path="password"/>
</td>
</tr>
</tbody>
</table>
<div>
<table>
<tr>
<td> </td>
<td>
<input type="button" class="btn blue px16" value="Search" />
<input type="button" name="submit" id="btnsubmit" value="Submit" onclick="setHiddenVal();"/>
<input type="button" class="btn blue px16" value="Clear" />
<input type="button" class="btn blue px16" value="Change Password" />
<input type="button" class="btn blue px16" value="Manage User Notification Profile" />
</td>
</tr>
</table>
</div>
</form:form>
</div>
</div>
<div class="clear"></div>
</div>
</div>
</div>
</body>
</html>
so above one is my code for jsp and below is the code of controller
#RequestMapping(value={"/usermaster" }, method = RequestMethod.POST)
public final String addUserMaster(#ModelAttribute("CustomerForm") CustomerForm pricing, Map<String, Object> map,
Model model, HttpServletRequest request) {
System.out.println("the first name is "+pricing.getFirstname());
System.out.println("the password is "+pricing.getPassword());
return "usermaster";
}
#RequestMapping(value={"/showusermaster" }, method = RequestMethod.GET)
public String showPage(ModelMap model){
model.addAttribute("CustomerForm", new CustomerForm());
return "usermaster";
}
But my page gets open up using a popup with the url:
C:\Users\ganganshu.s\AppData\Local\Microsoft\Windows\Temporary Internet Files\Content.IE5\YW6383E8\usermaster
so it should open like
http://localhost:8080/enbee/usermaster
Could you please tell me what should I put in the form action.. as I think some mistake is there in the form action does in spring MVC we put the action like in the case I mentioned above.
Spring confg file is given below :
<mvc:interceptors>
<bean class="com.enbee.admin.interceptor.AuthenticationInterceptor" />
<!-- Declare a view resolver-->
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" p:order="1" />
and the jsp name is usermaster.jsp
and in the sidemenu.jsp I have changed to this :
<li>User Master</li>
Change the method parameter of RequestMapping annotation to RequestMethod.POST:
#RequestMapping(value="/usermaster", method = RequestMethod.POST)
public final String addUserMaster(...){
...
}
so that when you submit your form to the URL /usermaster using method="POST" this method will get executed.
You also need to have a method (mapped to an URL) that will show this page to the user. You can use a method as below for this:
#RequestMapping(value = "/showusermaster", method = RequestMethod.GET)
public String showPage(ModelMap model){
model.addAttribute("CustomerForm", new CustomerForm());
return "usermaster";
}
With this method in place, the URL
http://localhost:8080/enbee/showusermaster
will show the usermaster.jsp page to the user. Now when you submit this form, the above addUserMaster method will be invoked.
You don't have to create new jsp file. The url /showusermaster will return the usermaster.jsp to the user, where the user can add form values and submit the form:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
...
<c:url var="submitUrl" value="/usermaster">
<form:form id="form" action="${submitUrl}" modelAttribute="CustomerForm" method="POST">
Now when the user clicks on the submit button, this form will be submitted to /usermaster URL and will be handled by addUserMaster method.
Try to specify the content type returned by your controller method, adding produces = "text/html" param to your #RequestMapping annotation.
I am trying to post a form using dojo.xhrPost. Below code works fine in chrome but does not work at all in Firefox. When I say it doesn't work I see that page reloads again and nothing happens. I tried to use dojo.stopEvent(event); but doesn't seem to work in Firefox.
Can you please suggest me what could be my mistake. I feel the issue is more with the form than with xhrPost.
HTML Looks like below:
<div data-dojo-type="dijit/form/Form" data-dojo-id="myform" id="loginform"
encType="multipart/form-data" action="" method="post">
<script type="dojo/method" data-dojo-event="onSubmit">
if(this.validate()){
senddata(); //calling the javascript function
}else{
alert('Form contains invalid data. Please correct first');
return false;
}
return true;
</script>
<table cellspacing="10">
<tr>
<td><label for="name">Username:</label></td>
<td><input type="text" id="username" name="username"
required="true" placeholder="Your UserName" data-dojo-
type="dijit.form.ValidationTextBox"/></td>
</tr>
<tr>
<td><label for="password">Password:</label></td>
<td><input type="password" id="password" name="password"
required="true" placeholder="Your Password"
data-dojotype="dijit.form.ValidationTextBox"/></td>
</tr>
</table>
<div id="response" style="float: right"></div>
<button data-dojo-type="dijit.form.Button" type="submit" name="submitButton"
value="Submit" style="float: right;">Submit</button>
</div>
My Javascript code is below:
function senddata(){
dojo.stopEvent(event);
obj = {};
obj.user_name =dijit.byId("username").get("value");
obj.password =dijit.byId("password").get("value");
var xhrArgs = {
url: "./script/php/validatelogin.php",
postData: obj,
handleAs: "json",
load: function(data){
//alert('success');
if(data.success==true){
window.location = data.message;
dojo.byId("response").innerHTML = "Form posted.";
}else{
dojo.byId("response").innerHTML = "login Failed";
}
},
error: function(error){
console.log("error occured!!!");
dojo.byId("response").innerHTML = "Failed to Post the Form..";
}
};
//alert('starting');
var deferred = dojo.xhrPost(xhrArgs);
//alert('done');
return false;
}
First, change the data-dojo-type into path format. E.g.: dijit/form/ValidationTextBox
Second, fix your typing mistake in password field of data-dojo-type. You entered data-dojotype, missing the - b=in between 'dojo' & 'type'
More information about dojo.byId() & dijit.byId().
Here is the result:
<div data-dojo-type="dijit/form/Form" data-dojo-id="myform" id="loginform" encType="multipart/form-data" action="" method="post">
<script type="dojo/method" data-dojo-event="onSubmit">
if(this.validate()){
senddata(); //calling the javascript function
}else{
alert('Form contains invalid data. Please correct first');
return false;
}
return true;
</script>
<table cellspacing="10">
<tr>
<td><label for="name">Username:</label></td>
<td><input type="text" id="username" name="username" required="true" placeholder="Your UserName" data-dojo-type="dijit/form/ValidationTextBox" /></td>
</tr>
<tr>
<td><label for="password">Password:</label></td>
<td><input type="password" id="password" name="password" required="true" placeholder="Your Password" data-dojo-type="dijit/form/ValidationTextBox" /></td>
</tr>
</table>
<div id="response" style="float: right"></div>
<button data-dojo-type="dijit/form/Button" type="submit" name="submitButton" value="Submit" style="float: right;">Submit</button>
</div>
<script>
function senddata(){
dojo.stopEvent(event);
obj = {};
obj.user_name =dijit.byId("username").get("value");
obj.password =dijit.byId("password").get("value");
var xhrArgs = {
url: "./script/php/validatelogin.php",
postData: obj,
handleAs: "json",
load: function(data){
//alert('success');
if(data.success==true){
window.location = data.message;
dojo.byId("response").innerHTML = "Form posted.";
}else{
dojo.byId("response").innerHTML = "login Failed";
}
},
error: function(error){
console.log("error occured!!!");
dojo.byId("response").innerHTML = "Failed to Post the Form..";
}
};
//alert('starting');
var deferred = dojo.xhrPost(xhrArgs);
//alert('done');
return false;
}
</script>
Strange bug I'm getting. I have a login form that is hidden by default, once a user clicks on an observed element, the element containing the form slides down (using Effect.BlidnDown in Scriptaculous)
Here is the function, which is part of the 'Interface' object:
revealLoginForm: function() {
$('a_login').blur();
if (!$('hform').visible()) {
Effect.BlindDown('hform', {
duration: 0.4,
afterFinish: function() {
$('f_login').focusFirstElement();
}
});
} else {
$('f_login').focusFirstElement();
}
},
The event observation:
Event.observe('a_login', 'click', Interface.revealLoginForm);
And the HTML:
<a id='a_login' href='javascript:void(0);'>Login to My Account</a>
....
<div id='hform' style='display:none;'>
<form id='f_login' action='...' method='post' name='sidelogin'>
<table cellspacing='0' class='login'>
<tr>
<th>Login ID:</th><td><input style='padding:2px;' type='text' size='18' name='enc_loginname' /></td>
</tr>
<tr>
<th>Password:</th><td><input style='padding:2px;' type='password' size='18' name='enc_password' /></td>
</tr>
<tr>
<th></th><td><input type='submit' class='submit' value='Login ยป' /></td>
</tr>
</table>
</form>
</div>
If I disable the $('f_login').focusFirstElement(); command in revealLoginForm(), the form does not disappear. What's strange is, the other call to this function does not adversely affect the element, it only seems to happen when called within the afterFinish callback to the Effect.BlindDown function.
Any ideas? It would be nice to have the first element of this form selected once the form has appeared. This works fine in Firefox.. it's just IE (Im using IE7) that's causing problems (go figure...)