I have a table that sends a form post of 5 input text with values to servlet. In servlet I get the values and set them into bean class, and the sum that I set it too to bean class as sum.Then I get the values and the sum on the jsp table.The problem, is that now Im creating a button that when I click, I insert a row after the last row, and I want to keep the values too with the sum, How can I do it?
This is my jsp that send the form to Servlet: Test.jsp
<jsp:useBean id="helloBean" scope="request" class="user.HelloBean" />
<form method="post" action="Servlet">
<table id= "sum_table">
<tr>
<td>Test</td>
<td>Total</td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td><input type="text" value="Test1" maxlength=25></td>
<td><input type="text" value="${helloBean.sum}" maxlength=3 readonly="readonly"></td>
<c:forEach items="${helloBean.values}" var="item">
<td><input type="text" id="val" name="values" value="${item}" maxlength=2/></td>
</c:forEach>
</tr>
</table>
<p><input type="submit"/></p>
<input type="button" id="btnAdd" value="+"/>
</form>
Now I got the values on servlet, calculate the sum and send them to java bean: Servlet.java
HelloBean hello = new HelloBean();
String[] values = request.getParameterValues("values");
if (values == null) {
values = new String[5];
for(int i = 0; i < 5; i++) {
values[i]= "0";
}
}
Integer sum = 0;
for (int i = 0; i < values.length; i++) {
hello.setSum(sum = sum + Integer.valueOf(values[i]));
hello.setValues(values);
}
request.setAttribute("helloBean", hello);
request.getRequestDispatcher("/Test.jsp").forward(request, response);
And this is my Bean Class: HelloBean.java
public class HelloBean {
String[] values;
Integer sum;
public Integer getSuma() {return sum;}
public void setSum(Integer integer) {this.sum = integer;}
public String[] getValues() {return values;}
public void setValues(String[] val) {this.values = val;}
}
This is how I add a new row:
$("#btnAdd").click(function () {
var row = $("#sum_table tbody > tr:last"),
newRow = row.clone(true);
newRow.find("input").each(function () {
var num = +(this.id.match(/\d+$/) || [0])[0] + 1;
this.id = this.id.replace(/\d+$/, "") + num;
this.name = this.id;
});
newRow.insertAfter(row);
return false;
});
Thank You in Advance!
Simply put a check on the value of sum in JSP page and based on its value add new row.
pseudo code:
if sum is not null then
add a new row in JSP
When page is loaded first time the value of the sum will be null and when redirected by servlet the value is populated and the sum will not be null and a new row is automatically created in the JSP page.
It should be like this and keep in mind the integer overflow problem.
int sum=0;
for (int i = 0; i < values.length; i++) {
sum = sum + Integer.valueOf(values[i]);
}
hello.setValues(values);
hello.setSum(sum);
It should look like in JSP:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<tr>
<td><input type="text" value="Test1" maxlength="25"/></td>
<c:forEach items="${helloBean.values}" var="item">
<td><input type="text" name="values" value="${item}" maxlength="2"/></td>
</c:forEach>
</tr>
<c:if test="${helloBean.sum != null}">
<tr>
<td><input type="text" value="${helloBean.sum}" maxlength="3" readonly="readonly"/></td>
</tr>
</c:if>
Some points:
ID must be unique in the whole page. Multiple input components are created with the same id val in the loop.
Use double quotes around the attribute values of the each tag. Is it typo?
property sum is not readable on type user.HelloBean because there is no getSum() method in class.
Don't need the Bean class
You can add keyup event for input
<form method="post" action="Servlet">
<table id= "sum_table">
<tr>
<td>Test</td>
<td>Total</td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td class="test"><input type="text" name="test" value="Test1" maxlength=25></td>
<td class="sum"><input type="text" name="sum" value="" maxlength=3 readonly="readonly"></td>
<td><input type="text" name="mark1" value="" maxlength=2 ></td>
<td><input type="text" name="mark2" value="" maxlength=2 ></td>
<td><input type="text" name="mark3" value="" maxlength=2 ></td>
<td><input type="text" name="mark4" value="" maxlength=2 ></td>
<td><input type="text" name="mark5" value="" maxlength=2 ></td>
</tr>
</table>
<p><input type="button" id="btnSubmit" value="Submit"/></p>
<input type="button" id="btnAdd" value="+"/>
<script>
$("#btnAdd").click(function () {
var row = $("#sum_table tbody > tr:last"),
newRow = row.clone(true);
newRow.find("input").each(function () {
var num = +(this.id.match(/\d+$/) || [0])[0] + 1;
this.id = this.id.replace(/\d+$/, "") + num;
this.name = this.id;
});
newRow.insertAfter(row);
return false;
});
$("#btnSubmit").click(function () {
$("#sum_table tbody tr").each(function() {
var row_total = 0;
$("td:not('.test'), td:not('.sum') input:text",this).each(function() {
var val =$.trim($(this).val());
//console.log('val='+val);
if(val!="" && !isNaN(val))
row_total += Number(val);
});
console.log('row_total='+row_total);
$(".sum :input:text",this).val(row_total);
});
});
</script>
-------------------SERVLET--------------
String[] test = request.getParameterValues("test");
String[] sum = request.getParameterValues("sum");
You can do it this way without using javascript for adding new row, if it helps you.
1) - Add name to the add button
<input type="button" id="btnAdd" ***name="addrow"*** value="+"/>
2) - At Servlet side check if add button is clicked
if (request.getParameter("addrow") != null){
request.setAttribute("addRow","yes");
}
3) - At Jsp side add below your for loop
<c:if test="${not empty request.addRow}">
<td><input type="text" id="val" name="values" value="" maxlength=2/></td>
</c:if>
This will add new emty text field whenever you click on the button.
NOTE: I did not test this code.
Just Replace with your input code I added "values[]" instead of "values"
You can use it as array and also set keys into it
<input type="text" id="val" name="values[]" value="${item}" maxlength=2/>
Related
I need to get disabled from <input> tag.
HTML snippet is like:
<tr>
<td><input type="radio" name="orderChoice" value="1" checked></td>
<td>Audi A4, Auto, A/C, $50.00/day</td>
<td>user</td>
<td>Иванов Иван Иванович 1983-10-03 АВ954326 Святошинським РУ ГУ МВС України у м. Києві 2001-06-05</td>
<td>2021-07-10 18:00:00.0</td>
<td>2021-07-20 14:00:00.0</td>
<td>500.00</td>
<td> <input type="checkbox" name="processed" disabled> </td>
<td> <input type="checkbox" name="rejected" disabled> </td>
<td></td>
<td> <input type="checkbox" name="picked" disabled> </td>
<td> <input type="checkbox" name="returned" disabled> </td>
<td> <input type="checkbox" name="damaged" disabled> </td>
<td></td>
<td></td>
<td> <input type="checkbox" name="paid" disabled> </td>
</tr>
I have the loop which looks like:
for (Element tableRow : tableRows) { // iterate over all the table rows (tr elements)
Element row = tableRows.get(tableRow.elementSiblingIndex());
String vehicle = row.select("tr > td").get(1).text();
Element td = row.select("tr > td").get(10); // <td> <input type="checkbox" name="picked" disabled> </td>
Elements checkbox = td.select("td > input[type=checkbox]"); // <input type="checkbox" name="picked" disabled>
String picked = checkbox.attr("name"); // picked
tableList.add(new Table(picked, vehicle));
}
and I need to get disabled from input tag.
Can someone suggest me, please, the way how can I get it without specifying the value explicitly, since checkbox can be changed dynamically?
Thanks to #PeterMmmm and #dan1st suggestions, I've solved using attributes().hasKey("disabled") and first() methods like:
for (Element tableRow : tableRows) { //iterate over all the table rows (tr elements)
Element row = tableRows.get(tableRow.elementSiblingIndex());
String vehicle = row.select("tr > td").get(1).text();
Element td = row.select("tr > td").get(10);
Element input = td.select("td > input[type=checkbox]").first();
Elements checkbox = td.select("td > input[type=checkbox]");
String picked = checkbox.attr("name");
if (input.attributes().hasKey("disabled")) {
//...
} else {
//...
}
}
I have 2 classes:
public class IndividualRate {
private String currency;
private String operation;
private double rate;
private double amount;
//controller, getters and setters
}
public class IndividualRateList {
private List<IndividualRate> individualRates = new ArrayList<>();
//controller, getters and setters
}
In JSp I have table and form tag for sending data to Spring:
<tbody id="rateBody">
<form:form method="POST" cssClass="forms" id="formRateSubmit" action="${urlRates}"
modelAttribute="individualRateList">
<tr id="row1">
<td>
<select name="individualRates[0].currency" id="listOfCurrency1">
<option selected="selected" value=""><spring:message code="label.please.select"/></option>
<c:forEach var="item" items="${currencyRates}" varStatus="loop">
<option value="${item.currency}" >${item.currency}</option>
</c:forEach>
</select>
</td>
<td>
<input type="radio" name="individualRates[0].operation" value="Buying" checked="true"/><spring:message code="label.buying.operation"/>
<input type="radio" name="individualRates[0].operation" value="Selling"/> <spring:message code="label.selling.operation"/>
</td>
<td>
<input type="text" name="individualRates[0].rate" id="txtRate1" size="10"/>
</td>
<td>
<input type="text" name="individualRates[0].amount" id="txtAmount1" size="10"/>
</td>
<td>
<a href="javascript:void(0);" id="deleteRow1" class="btn-remove"
style="color: #f00; text-decoration: none;" onclick="deleteRow('1')">X</a>
</td>
</tr>
<tr id="row2">
<td>
<select name="individualRates[1].currency" id="listOfCurrency2">
<option selected="selected" value=""><spring:message code="label.please.select"/></option>
<c:forEach var="item" items="${currencyRates}" varStatus="loop">
<option value="${item.currency}" >${item.currency}</option>
</c:forEach>
</select>
</td>
<td>
<input type="radio" name="individualRates[1].operation" value="Buying" checked="true"/><spring:message code="label.buying.operation"/>
<input type="radio" name="individualRates[1].operation" value="Selling"/> <spring:message code="label.selling.operation"/>
</td>
<td>
<input type="text" name="individualRates[1].rate" id="txtRate2" size="10"/>
</td>
<td>
<input type="text" name="individualRates[1].amount" id="txtAmount2" size="10"/>
</td>
<td>
<a href="javascript:void(0);" id="deleteRow2" class="btn-remove"
style="color: #f00; text-decoration: none;" onclick="deleteRow('2')">X</a>
</td>
</tr>
<%--</c:forEach>--%>
</form:form>
</tbody>
When I run this program both of 2 rows are sent to Spring. But the count of rows are mutable. I have button for adding new rows. If I comment second row (row2) and add this with addRow button second row isn't sent. The onClick function for addRow button:
$('#addRow').click(function () {
i = i + 1;
var row = document.getElementById("row1").cloneNode(true);
row.id = "row" + i;
var elementsInput = row.getElementsByTagName("input"); // 4 input tag
var elementSelect = row.getElementsByTagName("select"); // 1 select tag
//// Currency
elementSelect[0].id = "listOfCurrency" + i;
elementSelect[0].name = "individualRates[" + (i-1) + "].currency";
//// Operation
elementsInput[0].name = "individualRates[" + (i-1) + "].operation";
elementsInput[1].name = "individualRates[" + (i-1) + "].operation";
//// Rate
elementsInput[2].id = "txtRate" + i;
elementsInput[2].name = "individualRates[" + (i-1) + "].rate";
//// Amount
elementsInput[3].id = "txtAmount" + i;
elementsInput[3].name = "individualRates[" + (i-1) + "].amount";
document.getElementById("rateBody").appendChild(row);
});
Please, help me to solve this problem.
This is my jsp page that retrieve the list of items from database using for loop
<%
itemManager mgr = new itemManager();
Item[] items = mgr.getAllItems();
for(int i = 0; i < items.length; i++){
%>
<tr>
<td> <img border="0" src="<%=items[i].getItemImage() %>" width="100" height="100">
</td>
<td>
<%=items[i].getItemName()%>
<input type="text" name="itemID" value="<%=items[i].getItemID()%>">
<br/>
<%=items[i].getItemDesc()%>
<br/>
Start Bid : <%=items[i].getStartBid()%>
<br/>
Buy it now : <%=items[i].getEndBid()%>
<br/>
Bidding close on : <%=items[i].getDuration()%>
<br/>
<input type="submit" value="View">
<%
}
%></table>
This is the jsp page that link to the item you selected previously
<table border="1" align="center">
<%
itemManager mgr = new itemManager();
Item items = mgr.getItem((Integer)session.getAttribute("ITEM_DATA"));
%>
<tr>
<td> <b> <%=items.getItemName() %></b> </td>
</tr>
</table>
This is the servlet to store the session of the selected item id and forward to the correct item jsp page.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(true);
int id = Integer.parseInt(request.getParameter("itemID"));
session.setAttribute("ITEM_DATA",id);
RequestDispatcher rd = request.getRequestDispatcher("viewItem.jsp");
rd.forward(request, response);
}
However, after I clicked the view button. It keeps linking to the itemID = 1.
The URL dispalys "/ItemServlet?itemID=1&itemID=2" .
In fact, if I click on itemID=2 the URL should display like this:
"/ItemServlet?itemID=2"
As a result, how can I achieve this? Thanks in advance!
The problem in your code is you are using a single form and dynamically creating Input box inside the form. So all the input box will be having same name. That's why when you submit the form all the input box values are sent as request parameters. I just reduced some part in your code for better under standing. Take this as your code
<form action="item" method="get">
<table>
<%
ItemManager mgr = new ItemManager();
Item[] items = mgr.getAllItems();
for(int i = 0; i < items.length; i++){
%>
<tr>
<td>
<%=items[i].getItemName()%>
<input type="text" name="itemID" value="<%=items[i].getItemId()%>">
<input type="submit" value="View"> </td></tr>
<%
}
%></table>
</form>
When you run this code and if you check the rendered HTML code it will be look
<form action="item" method="get">
<table>
<tr><td>
aaa
<input type="text" name="itemID" value="1">
<input type="submit" value="View"> </td></tr>
<tr>
<td>
bbb
<input type="text" name="itemID" value="2">
<input type="submit" value="View"> </td></tr>
<tr><td>
ccc
<input type="text" name="itemID" value="3">
<input type="submit" value="View"> </td></tr>
</table>
</form>
Here All the Input box having same name as "itemID". As a solution you can create the form inside the for loop, so that while submitting only one Input box value will be sent as request.
Create form inside your for loop like below code.
<table>
<%
ItemManager mgr = new ItemManager();
Item[] items = mgr.getAllItems();
for(int i = 0; i < items.length; i++){
%>
<form action="item" method="get">
<tr>
<td>
<%=items[i].getItemName()%>
<input type="text" name="itemID" value="<%=items[i].getItemId()%>">
<input type="submit" value="View"> </td></tr>
</form>
<%
}
%></table>
Hope This will help you.
change the name of text field dynamically.
And use getQueryString() in servlet to find the itemId name and value. by using EL.I hope this will help you
I have a problem to retrieve a value from a cell of a HTML table which is scrollable. I had revised some of the javascript codes but they don't seems to work. Please help me, I'm quite new to javascript. This is my following code:
Javascript
var rowIndex = 0;
var cellIndex = 0;
var nTable = "";
var nRows = 0;
var nCells = 0;
function showCoords(r,c)
{
rowIndex = r;
cellIndex = c;
if(r!=0 && nTable.rows[r].cells[c].tagName != "th")
{
var selectedValue = nTable.rows[r].cells[0].innerHTML;
document.getElementById('celldata1').value=selectedValue;
var selectedValue = nTable.rows[r].cells[1].innerHTML;
document.getElementById('celldata2').value=selectedValue;
var selectedValue = nTable.rows[r].cells[2].innerHTML;
document.getElementById('celldata3').value=selectedValue;
}
}
function getCoords(currCell)
{
for (i=0; i<nRows; i++)
{
for (n=0; n<nCells; n++)
{
if (nTable.rows[i].cells[n] == currCell)
{
showCoords(i,n);
}
}
}
}
function mapTable()
{
nTable = document.getElementsByTagName("table")[1]
nRows = nTable.rows.length;
nCells = nTable.rows[0].cells.length;
for (i=0; i<nRows; i++)
{
for (n=0; n<nCells; n++)
{
nTable.rows[i].cells[n].onclick = function()
{
getCoords(this);
}
nTable.rows[i].cells[n].onmouseover = function()
{
this.style.cursor = 'pointer';
}
}
}
}
onload=mapTable;
I'm not sure if the above javascript codes getting wrong either in their syntax or logic, but I'll be glad if somebody help me to point them out.
HTML code:-
head
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>My Content</title>
<link rel="stylesheet" text="css/text" href="mycss.css" title=""></link>
<script type ="text/javascript" src="test.js"></script>
</head>
body part 1
This is the part where I want the values to show up in each textbox accordingly from each cell of tableone.
<body>
<table border="0">
<tbody>
<tr>
<td>Content 1:</td>
<td><input id="celldata1" type="text" name="content1" value="" /></td>
</tr>
<tr>
<td>Content 2:</td>
<td><input id="celldata2" type="text" name="content2" value="" /></td>
</tr>
<tr>
<td>Content 3:</td>
<td><input id="celldata3" type="text" name="content3" value="" /></td>
</tr>
</tbody>
</table>
body part 2
This is tableone.
<table border="1" id="tableone">
<thead>
<tr>
<th>Item</th>
<th>Content 1</th>
<th>Content 2</th>
<th>Content 3</th>
</tr>
</thead>
<tbody>
<%! int i;%>
<%for(int i=0; i<50; i++){%>
<tr>
<td><%=i+1%></td>
<td></td>
<td></td>
<td></td
</tr>
<%}%>
</tbody>
</table>
</div>
Thanks by the way and sorry if my English is not good :)
I use jQuery for this:
// Iterate throught rows of table:
jQuery("table").find("tr").each( function() {
var currentRow = jQuery(this);
// Iterate throught cell in current row:
currentRow.find("td").each(function() {
var currentCell = jQuery(this);
// Do what you want with cell
});
});
I have a multi-select Box and I'm doing some javascript to sort the order of the elements in the box. I want to submit the whole array after sorting back to the Java and not just the select items. How can I achieve this?
JSP:
<script type="text/javascript">
$(document).ready(function(){
$("#mup")[0].attachEvent("onclick", moveUpItem);
$("#mdown")[0].attachEvent("onclick", moveDownItem);
});
function moveUpItem(){
$('#list option:selected').each(function(){
$(this).insertBefore($(this).prev());
});
}
function moveDownItem(){
$('#list option:selected').each(function(){
$(this).insertAfter($(this).next());
});
}
</script>
<table width="100%">
<tr>
<td width="50%" align="center">
<h1>DET Column Maintenance</h1>
</td>
</tr>
</table>
<form action="process.det_column_order" method="post" name="detColumnSortorder" >
<table class="data_table">
<tr align="center">
<td>
<select id="list" name="fieldNames" size="35" multiple="multiple" style="width: 250px;">
<c:forEach var="field" items="${detFields}">
<option value="${field.fieldName}">${field.displayName}</option>
</c:forEach>
</select>
</td>
<tr>
<td style="text-align: center;">
<button id="mup">Move Up</button>
<button id="mdown">Move Down</button>
</td>
</tr>
<tr>
<td style="text-align: center;">
<input name="action" type="submit" value="Submit"/>
</td>
</tr>
</table>
</form>
FORM:
private String[] fieldNames;
public String[] getFieldNames() { return this.fieldNames; }
public void setFieldNames(String[] val) { this.fieldNames = val; }
Since forms only submit the selected values, you'll need a little more JS and another form field.
Introduce a hidden form field that will hold the values you care about:
<input type="hidden" name="fieldNamesOrder" id="fieldNamesOrder"/>
And after every click of Move Up/Move Down:
var order = [], sel = document.getElementById("list");
for(var i = 0, len = sel.options.length; i < len; i++) {
order.push(sel.options(i).value);
}
document.getElementById("fieldNamesOrder").value = order.join(",");
Then, on the server side, you can read your ordered field names out of that posted field.
You either need to create a hidden text field in your HTML form that stores the values from each of your options... or you need to programatically select all of the options before the form is submitted.