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
Related
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:
I am creating a page in thymeleaf where I retrieve a list from my controller to mount a table, in this table there is a selection field where I retrieve a list of values but I am not able to display the value that is already being retrieved of the database can help me? Please!
I already tried to use the following commands but could not recover the value:
th:field="*{valoresAtributo[__${stat.index}__].valorUsuario}"
I receive the following error: Neither BindingResult nor plain target object for bean name available as request attribute.
<table class="table table-sm table-striped table-bordered" id="dataTable">
<thead>
<tr><th colspan="4">Valores dos Atributos</th></tr>
</thead>
<tbody>
<tr class="text-black">
<td rowspan="2"> Atributo</td>
<td rowspan="2"> Local</td>
<td>Aplicação</td>
<td>Usuário</td>
</tr>
<tr>
<td id="vlAppl"></td>
<td id="vlUser"></td>
</tr>
<tr th:each="valorAtributo, stat : ${valoresAtributo}">
<td th:text="${valoresAtributo[__${stat.index}__].nomeAtributo}"></td>
<td th:text="${valoresAtributo[__${stat.index}__].valorLocal}"></td>
<td th:text="${valoresAtributo[__${stat.index}__].valorAplicaco}"></td>
<td>
<select class="form-control col-md-10" th:field="*{valoresAtributo[__${stat.index}__].valorUsuario}">
<option th:each="option : ${T(com.jequiti.JequitiIntegrador.controller.AtributoController).test(valorAtributo.sqlValidacao)}"
th:value="${{option.valorAtributo}}"
th:text="${option.significadoAtributo}">
</option>
</select>
</td>
</tr>
</tbody>
</table>
#RequestMapping(value="/seguranca/atributo/valores", params = {"atributo","siteOpt","applOpt","userOpt","aplicacao","usuario"}, method = RequestMethod.GET)
public String initAttributeValuesFormFilter(#RequestParam("atributo") Long idAtributo, #RequestParam("siteOpt") Integer idNivel1, #RequestParam("applOpt") Integer idNivel2, #RequestParam("userOpt") Integer idNivel3, #RequestParam("aplicacao") String aplicacao, #RequestParam("usuario") String usuario, Model model)
{
Integer userId = 0;
if(!Strings.isNullOrEmpty(usuario))
userId = userServiceImpl.findIdUsuarioByFantasia(usuario).intValue();
List<ValoresAtributoView> valoresAtributo = buscaValoresAtributos(idAtributo, idNivel1, idNivel2, idNivel3, 0, userId);
model.addAttribute("opUsuarios", userServiceImpl.findAllActiveUsers());
model.addAttribute("opAtributos", atributoService.findAll());
model.addAttribute("valoresAtributo",valoresAtributo);
return "/valoresAtributo";
}
I expected the field to display the value that is currently in the database and the options in the list of values.
Thank you all!
You can only use th:field if you are using th:object in a parent <form /> tag. (Which isn't clear from the HTML you posted -- but you probably are not since your are adding valoresAtributo directly as a model attribute.)
If you wish to show a preselected <option> but without using th:object and th:field you should instead use the th:selected attribute which should evaluate to true or false based on if that option should be selected. It should look something like this:
<select class="form-control col-md-10">
<option
th:each="option : ${T(com.jequiti.JequitiIntegrador.controller.AtributoController).test(valorAtributo.sqlValidacao)}"
th:value="${{option.valorAtributo}}"
th:text="${option.significadoAtributo}"
th:selected="${valorAtributo.valorUsuario == option.valorAtributo}" />
</select>
My way to retrieve list using thymeleaf:
For example list users with list of User entity getting to html page:
#GetMapping("/parsing/explorer")
public ModelAndView parsing(){
ModelAndView modelAndView = new ModelAndView("show");
modelAndView.addObject("users", generateUsersList());
return modelAndView;
}
show.html example:
<table class="w3-table-all w3-card-4">
<tr>
<th>Id</th>
<th>Name</th>
<th>Last name</th>
</tr>
<tr th:each="user : ${users}">
<td th:text="${user.getId()}"></td>
<td th:text="${user.getName()}"></td>
<td th:text="${user.getLastName()}"></td>
</tr>
</table>
So list of User (users) is assigned to the variable user in string <tr th: every = "user: $ {users}">
In the next block of code, we can also call the "User" fields the same way as java using getters, but Thymeleaf also allows you to refer to the fields: user.id/ user.name....
Determining variable in the select block:
<select name="userFromHtml" id=userId required>
<option th:each="user: ${users}">
<title th:text="${user.getLastName()} + ' ' + ${user.getName()} + ' ' + ${user.getIdIO}" th:value="${user.getId()}"/>
</option>
</select>
in this case is necessary to determine th:value in title block: th:value="${user.getId()}". So, in controller is passed variable userFromHtml with value id of selected user.
PS Although Thymeleaf allows you to define variable in direct, I prefer to use getters for data getting.
when i search specific word only first page is classified. it shows pages and posts well on first page.
but when i go to page 2 or next page, seaching keyword doesn't apply on
is this address problem?
i guess this is sql or Paging.java problem because when i print log of page at BDAO it shows page well which i clicked.
also I don't know how can i transfer keyWord &keyField for that..!
I use oracle DB.
<%
String keyWord = (String)request.getParameter("keyWord");
String keyField = (String)request.getParameter("keyField");
%>
<script>
function searchCheck(frm){
//검색
if(frm.keyWord.value ==""){
alert("검색 단어를 입력하세요.");
frm.keyWord.focus();
return;
}
frm.submit();
}
function PageMove(page){
var keyWord = '<%=keyWord%>'
var keyField = '<%=keyField%>'
console.log(keyWord);
if(keyWord !=''){
location.href = "list.do?page="+page+"&keyWord=" + keyWord + "&keyField=" + keyField;
}
location.href = "list.do?page="+page;
}
</script>
</head>
<body>
<table width="800" cellpadding="0" cellspacing="0" border="1">
<tr>
<td>번호</td>
<td>이름</td>
<td>제목</td>
<td>날짜</td>
<td>히트</td>
</tr>
<c:forEach items="${list}" var="dto">
<tr>
<td>${dto.bId}</td>
<td>${dto.bName}</td>
<td>
<c:forEach begin="1" end="${dto.bIndent}">-</c:forEach>
${dto.bTitle}</td>
<td>${dto.bDate}</td>
<td>${dto.bHit}</td>
</tr>
</c:forEach>
<tr>
<td colspan="5">
<form action="list.do" method="post" name="search">
<select name="keyField">
<option value="bTitle">글 제목</option>
<option value="bContent">글 내용</option>
<option value="bName">작성자</option>
</select>
<input type="text" name="keyWord">
<input type="button" value="검색" onclick="searchCheck(form)">
</form>
</td>
</tr>
<tr>
<td colspan="5"> 글작성 </td>
</tr>
</table>
<div class="toolbar-bottom">
<div class="toolbar mt-lg">
<div class="sorter">
<ul class="pagination">
<li>맨앞으로</li>
<li>앞으로</li>
<c:forEach var="i" begin="${paging.startPageNo}" end="${paging.endPageNo}" step="1">
<c:choose>
<c:when test="${i eq paging.pageNo}">
<li class="active">${i}</li>
</c:when>
<c:otherwise>
<li>${i}</li>
</c:otherwise>
</c:choose>
</c:forEach>
<li>뒤로</li>
<li>맨뒤로</li>
</ul>
</div>
</div>
</div>
You never seem to be passing the keyword or keyfield when you call pageMove(). You might as well look up their values inside the function instead of having them as parameters:
function PageMove(page){
var keyWord = document.getElementById("keyWord").value;
var keyField = document.getElementById("keyField").value;
location.href = "list.do?page=" + page + "&keyWord=" + keyWord + "&keyField=" + keyField;
}
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
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.