reusing Text field value in same jsp page - java

How can I use the value of text field which I enter from GUI again for further computation? I have following piece of code
<tr>
<td> Enter Index Value:</td>
<td><input type="text" title="Enter Index#" id="ind" name="index"
size="2" maxlength="2" /></td>
<td><input type="text" name="bid" value=<%= lm.book_ids.get(a-1)%>
style="visibility: hidden" /></td>
<td><input type="text" name="brid" value=<%= lm.branch_id.get(a-1)%>
style="visibility:hidden" /></td>
<td><input type="text" name="cardno" value=<%= lm.cards.get(a-1)%>
style="visibility: hidden" /></td>
</tr>
I want to use the value of text field in place of 'a' which is an arbitrary java int variable.

You cannot change the variables that way. Your scriptlets (which are bad design BTW as well) will only be run once when the JSP file is rendered into HTML. When the user has loaded the page, there's only the data given by the scriptlets left as text amidst HTML.
You'd either have to save the entire data structures into a Javascript array on page load and keep swapping the data based on index or then use AJAX to fetch new data from your server.
* EDIT *
Here's an example:
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var indexField = $("#ind");
var bidArray = new Array();
bidArray[0] = '<%= lm.book_ids.get(0) %>';
bidArray[1] = '<%= lm.book_ids.get(1) %>';
indexField.keyup(function() {
var index = indexField.val();
var bid = bidArray[index];
if (bid !== undefined) {
$("#bid").val(bid);
}
});
});
</script>
</head>
[...]
<tr>
<td>Enter index value:</td>
<td><input type="text" title="Enter Index#" id="ind" name="index"
size="2" maxlength="2" /></td>
<td><input type="hidden" id="bid" name="bid" /></td>
</tr>
And a JSfiddle.

Related

Replace GET request by POST without form in JSP

So i have this JSP page which having data from table and forming a GET request to render more data on another page , by clicking one of the table line
Problem is i have to transforming it into POST method , to avoid getting information in the http request link
i know how to use post with form, but here i have to take the date from a table line and not a form
Any idea how to do that. i'm new to JSP so i don't know how to do it
<table border=0 bgcolor=#92ADC2 cellspacing=1 cellpadding=3 width=95% align=center>
<tr class=entete>
<td class=texte8 align=center> <spring:message code="nom"/></td>
<td class=texte8 align=center> <spring:message code="date_naissance"/></td>
<td class=texte8 align=center> <spring:message code="numero"/></td>
</tr>
<%
String v_Person = "";
String v_date = "";
String v_numero = "";
for (int i = 0; i < PersonListeBean.getPerson(); i++)
{
Gen_rechBean cb = PersonListeBean.getPerson(i);
v_Person = cb.getname();
v_date=cb.getdate();
v_numero=cb.getNumero();
}
%>
<tr class="<%=class_cell%>" onMouseOver="this.className='over';" onMouseOut="this.className='<%=class_cell%>';" onclick="javascript:parent['gauche'].document.location='ResultServlet?name=<%=v_Person%>&numero=<%=v_numero%>&date_naissance=<%=v_date%>">
<td class=texte7 align=left > <%=cb.getname()%></td>
<td class=texte7 align=left > <%=cb.getdate()%></td>
<td class=texte7 align=left > <%=cb.getNumero()%></td>
</tr>
</table>
<br>
<table width="95%" align="center" border="0" cellspacing="0" cellpadding="0">
<tr>
<td align="right">
<a target="corps" href="rechResult.jsp" class="rub2" </a>
</td>
</tr>
</table>
I see what are you trying to do.
The easiest way to do that is using a form. So you can call a js method when you click the
<tr onclick="myMethod()">
that you want.
The method can fill your form and send the submit. Using this you can be redirected without sending data in you url.
A basic example could be:
(Supposing these are elements printed by server-side)
<tr onclick="myMethod(<%=getName()%>, <%=getDate()%>, <%=getNumero()%>)">
<td>...</td>
<td>...</td>
<td>...</td>
</tr>
<form id="myForm" action="targetFile.jsp" method="post">
//Hidden inputs to prevent users form touching this fields
<input type="hidden" name="name" id="data1">
<input type="hidden" name="date" id="data2">
<input type="hidden" name="numero" id="data3">
</form>
<script>
function myMethod(data1, data2, data3){
//Im gonna use jQuery. Is like javascript but quite faster to use
//Filling the form
$("#data1").val(data1);
$("#data2").val(data2);
$("#data3").val(data3);
//Submiting it
$("myForm").submit();
}
</script>
Let me know if it was helpful.
c:

INPUT with multiple values of multiple values each

Not sure the best way to do this...
I have an HTML FORM with multiple rows.. But one of the columns also has multiple values.
I know I can receive the event into a String array with getParamaterValues(). But for the variable days, how do I get that into an array of arrays so it's still related to the event column?
It's all coming out of a database so I can't just hard code it.
I'm sure I actually know the answer but my brain is not cooperating... Thanks in advance for the kick-start... I'm using Java servlets. But it's really just an HTML question.
e.g.
<tr>
<td>
<input type="checkbox" name="event" value="ev1">
<td>
<input type="checkbox" name="days" value="Sat">
<input type="checkbox" name="days" value="Sun">
<tr>
<td>
<input type="checkbox" name="event" value="ev2">
<td>
<input type="checkbox" name="days" value="Fri">
<input type="checkbox" name="days" value="Sat">
<input type="checkbox" name="days" value="Sun">
<tr>
<td>
<input type="checkbox" name="event" value="ev3">
<td>
<input type="checkbox" name="days" value="Sat">
<input type="checkbox" name="days" value="Sun">
<input type="checkbox" name="days" value="Mon">
Append the value from the events to the name attribute of the days like ev1_days, ev2_days, ev3_days:
<tr>
<td>
<input type="checkbox" name="event" value="ev1">
</td>
<td>
<input type="checkbox" name="ev1_days" value="Sat">
<input type="checkbox" name="ev1_days" value="Sun">
</td>
</tr>
...
...
Then you can do something like:
String[] events = request.getParamaterValues("event");
for(int i=0; i<events.length; i++)
{
String[] days = request.getParamaterValues(events[i] + "_days");
//do something with days....
}
You should actually close your td's and tr's by the way.
You will have to change name of Checkboxes that belongs to the same event to a unique name.
HTML
<tr>
<td>
<input type="checkbox" name="event" value="ev1">
<td>
<input type="checkbox" name="daysA" value="Sat">
<input type="checkbox" name="daysA" value="Sun">
<tr>
<td>
<input type="checkbox" name="event" value="ev2">
<td>
<input type="checkbox" name="daysB" value="Fri">
<input type="checkbox" name="daysB" value="Sat">
<input type="checkbox" name="daysB" value="Sun">
<tr>
<td>
<input type="checkbox" name="event" value="ev3">
<td>
<input type="checkbox" name="daysC" value="Sat">
<input type="checkbox" name="daysC" value="Sun">
<input type="checkbox" name="daysC" value="Mon">
Script
var events = [];
var daysA = [];
var daysB = [];
var daysC = [];
var jsonData="";
function c(){
var eventCB = document.getElementsByName("event");
var daysACB = document.getElementsByName("daysA");
var daysBCB = document.getElementsByName("daysB");
var daysCCB = document.getElementsByName("daysC");
for(var i=0;i<eventCB.length;++i){
events.push(eventCB[i].value);
}
for(var i=0;i<daysACB.length;++i){
daysA.push(daysACB[i].value);
}
for(var i=0;i<daysBCB.length;++i){
daysB.push(daysBCB[i].value);
}
for(var i=0;i<daysCCB.length;++i){
daysC.push(daysCCB[i].value);
}
jsonData ='{events:['+events.toString()+'],days:[['+daysA.toString()+'],['+daysB.toString()+'],['+daysC.toString()+']]}'
}
Passing data to Servlet
var jsonComplete = JSON.stringify(jsonData);//You will get below string
//{events:[ev1,ev2,ev3],days:[[Sat,Sun],[Fri,Sat,Sun],[Sat,Sun,Mon]]}
$.ajax({
url:"URLServlet",
type:"POST",
dataType:'json',
data: {jsonComplete : jsonComplete },
success:function(data){
// do whatever required
},
});
Receiving Data in Servlet Using org.json
JSONObject objJSON = new JSONObject(request.getParameter("jsonComplete "));
JSONArray arrEvents = objJSON.getJSONArray("events");
JSONArray arrDays = objJSON.getJSONArray("days");
for(int i=0;i<arrEvents.length();++i){
out.println("event["+i+"]:"+arrEvents.getString(i));//Similar to event[0]:ev1
}
for(int i=0;i<arrDays.length();++i){
JSONArray arrDaystemp = arrDays.getJSONArray(i);
out.println("days["+i+"]:[");
for(int i=0;i<arrDaystemp.length();++i){
out.println(arrDaystemp.getString(i));//Similar to days[0]:[Mon,Tue]
}
out.println("]");
}

How to write Java code inside of innerHTML

My requirement is as below.
Whenever user clicks on Additem button One new row should be added in the table.(Table Name : additionalInfoTable).
The must have three cells.
First two cells must have Text field.
Second cell must have dropdown with a list of Values.
For this I have written code in Javascript as below. But When I generate dropdown values from Java ArrayList, Java snippet is not running inside InnerHTML.
function addAdditionalRow() {
var table = document.getElementById("additionalInfoTable");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.innerHTML = '<input type="text" size="15" name="additionalCost" />';
cell2.innerHTML = '<input type="text" size="15" name="totalCost" />';
cell3.innerHTML = '<select name="recoveryType">'+
'<option>--Select Recovery Type--</option>';
<% for(String recType: details.getRecoveryTypeList()) { %>
var recType = '<%=recType%>';
cell3.innerHTML = '<option value="'+recType+'">'+recType%+'</option>';
<%}%>
cell3.innerHTML = '</select>';
cell4.innerHTML = '<input type="button" value="Delete" onclick="deleteRow(this)"/>';
}
My JSP code for the table is below.
<table border ="1" width="100%" id="additionalInfoTable">
<thead>
<tr>
<td align="center" ><b>Additional Cost $</b></td>
<td align="center" ><b>Total Cost</b></td>
<td align="center" ><b>Recovery Type</b></td>
<td align="center" ><b>Delete</b></td></tr>
</tr>
</thead>
<tbody id="addBillbackdata">
<tr>
<td align="center">
<input type="text" size="15" name="additionalCost" />
</td>
<td align="center">
<input type="text" size="15" name="totalCost" />
</td>
<select name="recoveryType">
<option>--Select Recovery Type--</option>
<% for(String recType: details.getRecoveryTypeList()) { %>
<option value="<%=recType%>"><%=recType%></option>
<%}%>
</select>
</td>
<td align="center">
<input type="button" value="Delete" onclick="deleteRow(this)"/>
</td>
</tr>
</tbody>
</table>
Please help me to get Java ArrayList values inside innerHTML of javascript
Your javascript modifies the HTML in the browser. JSP code is compiled serverside before it is being delivered to the browser. It is not possible to use JSP code in javascript, because the browser has no way of interpreting it. You have to either
create the desired html with jsp, hide it (e.g. with display:none), and attach it dynamically with javascript
create a global javascript variable in jsp within a <script>-Tag and reference it from your button callback
create a different jsp or servlet to deliver the data and use AJAX to request it

unable to add or update records in servlet /jsp

I'm trying to submit form with post method like :
<form action="/context/controller" method="post">
<input type="hidden" name="update" value="add_record"/>
<table>
<tr>
<td>Name : </td>
<td><input type="text" name="u_name" /></td>
</tr>
<tr>
<td>Visible :</td>
<td>
<input type="radio" name="visible" value="0"/> No
<input type="radio" name="visible" value="1"/> Yes
</td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Add record"/>
<input type="reset" value="Reset"/></td>
</tr>
</table>
</form>
and I'm getting form data in doPost() of controller servlet as :
String updateParam = request.getParameter("update");
System.out.println("Param value : " + updateParam);
if (updateParam.equals("add_record")) {
recordDAO = new RecordDAO();
System.out.println("add if true Param value : " + updateParam);
Record record = new Record();
String name = request.getParameter("u_name");
String visible = request.getParameter("visible");
record.setName(name);
subject.setVisible(visible);
recordDAO.addRecord(record);
request.getRequestDispatcher("/view.jsp").forward(
request, response);
}
this line
System.out.println("Param value : " + updateParam);
prints Param value : add_record on the console but if condition never becomes true, thus I'm unable to add records, please tell me where is my bug which is preventing code of if condition from execution.
There is one whitespace before "add_record", that's why your condition never becomes true.
So modify your condition to if (updateParam.equals(" add_record")) { or, which I prefer, modify your parameter to output the string without whitespaces.

Updating list after insert new items through a JSP form

In my Spring project, I am passing a List to my JSP page from my controller in this way:
mav.addObject("tipos", tipo.listaTipos());
mav.addObject("campos", atributo.listaKey());
In the JSP page, besides display this items, I can add new items too, as demonstrated in the code below (both HTMl and Jquery):
HTML
<table class="bordered campos" id="edit_campos">
<thead>
<tr>
<th>Campo</th>
<th>#</th>
</tr>
</thead>
<tfoot>
<tr>
<td> <input type="text" name="nome_campo"> </td>
<td> <button type="button" id="incluir_campo" class="btn btn-link">Incluir</button> </td>
</tr>
</tfoot>
<c:forEach var="item_key" items="${campos}">
<tr id="linha_${item_key.id}">
<td> <input type="text" name="${item_key.nome}" value="${item_key.nome}"> </td>
<td> <button type="button" id="excluir_campo" class="btn btn-link">Excluir</button> </td>
</tr>
</c:forEach>
</table>
JQuery
$("#incluir_campo").on("click", function () {
$.ajax({
type: "GET",
url: "<c:out value="${pageContext.request.contextPath}/key/cadastra_campo"/>",
data: {nome: $("input[name=nome_campo]").val() }
}).done(function(data){
if(data=="yes") {
var newRow = $("<tr>");
cols = '<td> <input type="text" name="${item_key.nome}" value="${item_key.nome}"> </td>';
cols += '<td> <button type="button" id="excluir_campo_${item_campo.id}" class="btn btn-link">Excluir</button> </td>';
newRow.append(cols);
$("table.campos").append(newRow);
$("input[name=nome_campo]").val("");
}
else {
alert("erro ao incluir campo");
}
}).fail(function(){
alert("falha ao incluir campo");
});
});
But, in this current scenario, the new lines are display with no content, due the list passed to JSP remains the same. How I can update the list I passed to my JSP after I insert a new item?
Look at these lines:
cols = '<td> <input type="text" name="${item_key.nome}" value="${item_key.nome}"> </td>';
cols += '<td> <button type="button" id="excluir_campo_${item_campo.id}" class="btn btn-link">Excluir</button> </td>';
Don't use expressions(${}) in Jquery when you working dynamically with DOM elemnts like insert new, update DOM etc, expressions are evaluated when jsp is processed/rendered HTML.
Solution will be:
After getting new item in Controller add it to list, and return the same item as response to AJAX, then append it to exists table. like:
consider your controller method returns data in json like:
var data = {"item_key" : {nome : "abc"}, "item_campo" : {id : "1"}};
then in done do like:
.done(function(data){
if(data.length != 0) {
var $newRow = $("<tr>");
var $newTextbox = $('<input type="text" id="'+data.item_key.nome+'" name="foo">');
var $newButton = $('<button type="button" id="excluir_campo_'+data.item_campo.id+'" class="btn btn-link">Excluir</button>');
$newRow.append($('<td>').append($newTextbox));
$newRow.append($('<td>').append($newButton));
$("table.campos").append($newRow);
$("input[name=nome_campo]").val("");
}
else {
alert("erro ao incluir campo");
}
})
jsfiddle

Categories