I am using this scriplet within my jsp:
<%
String q3 = request.getParameter ("checkbox1");
session.setAttribute("q3", q3);
%>
This will get the values from these checkboxes
<p> Which of the following are associated with Threading? Select two </p>
<input type="checkbox" name="checkbox1" value="LiveLock">LiveLock<br>
<input type="checkbox" name="checkbox1" value="Stack Overflow">Stack Overflow<br>
<input type="checkbox" name="checkbox1" value="Heap">Heap<br>
<input type="checkbox" name="checkbox1" value="Starvation">Starvation<br>
<input type="submit" value="Next" >
Or rather..thats what it should do. But when i grab the values and print them out as so
<p>Good day <%= session.getAttribute("uname") %> </p>
<p>For question 1 you chose <%= session.getAttribute("q1") %> </p>
<p>For question 2 you chose <%= session.getAttribute("q2") %> </p>
<p>For question 3 you chose <%= session.getAttribute("q3") %> </p>
<p>For question 4 you chose <%= session.getAttribute("q4") %> </p>
The radio buttons for q1,2,4 work fine. the check box will only return the first value that is checked or rather. The value that comes first i.e. if i select "Heap" and then "Livelock", in the print outs it will display "LiveLock"
you should use request.getParameterValues() instead of request.getParameter() because checkbox names are same.
Remember that getParameterValues() returns array so you have to do
String q3[] = request.getParameter ("checkbox1");
and for retrieving values iterate it like below
for(String s:q3)
{
System.out.println(s);
}
for printing in the browser
you can do
for(String s:q3)
{
out.println(s);
}
Use request.getParameterValues to get multiple checkbox selection:
String[] q3 = request.getParameterValues ("checkbox1");
Store in session:
session.setAttribute("q3", request.getParameterValues("checkbox1"));
Traverse to display values:
<p>Good day <%= session.getAttribute("uname") %> </p>
<p>For question 1 you chose
<%String[] ans = (String[])session.getAttribute("q3");
for(String chkd : ans) {
out.print(chkd);
out.print(", ");
}%>
</p>
Note: use of scriplets are not recommended.
Related
I have dropdown with options and the values. I can get the option value by the dropdown name in servlet but how can i get the dropdown "value" in servlet. In screenshot, temporarily i concatenated the with options but i want to store value in variable in servlet.
Please help:
HTML:
<input type="text" name="taxiDropdown" id= "taxiDropdown" placeholder="Search taxi...">
</div>
<div class="scrolling menu">
<%
List eList = (ArrayList) session.getAttribute("taxiInfo");
%>
<%
for (int i = 0; i < eList.size(); i++) {
%>
<div class="item" data-value="<%=((TaxiInfo) eList.get(i)).getID()%>">
<div class="ui green empty circular label"></div>
<%=((TaxiInfo) eList.get(i)).getTaxiPlate() +" "+ ((TaxiInfo) eList.get(i)).getID() %>
</div>
<%
}
%>
</div>
</div>
Servlet:
String val = request.getParameter("taxiDropdown");
(in "val", I want to store the value of the dropdown not the option text)
In JSP you should have something like that:
<form method="post">
<select name="taxiDropdown" id="taxiDropdown">
<%
List<TaxiInfo> eList = (List<TaxiInfo>) request.getAttribute("taxiInfo");
for (TaxiInfo taxiInfo : eList) {
%>
<option name="<%=taxiInfo.getTaxiPlate()%>" value="<%=taxiInfo.getID()%>"><%=taxiInfo.getTaxiPlate()%></option>
<%
}
%>
</select>
<input type="submit" />
</form>
Then in controller/servlet you will receive the id of TaxiInfo:
String val = request.getParameter("taxiDropdown");
System.out.println(val);
Or in your case you should set a hidden input with javascript with desired value.
added this code in html:
Move value of the dropdown selection to hidden textbox
<script type='text/javascript'>
$(function() {
$('#driverdp').change(function() { <-- this is my dropdown -->
var x = $(this).val();
$('#driverid').val(x); <-- this is my textbox -->
});
});
</script>
Servlet:
get the value of hidden text in servlet
String text= request.getParameter("driverId");
hope it will help someone
I've a JSP, where I display elements through JSTL c:forEach loop. This is a nested loop as shown below:
<c:forEach items="${auditBudgetData.auditBudgetTierOneList}" var="auditBudgetTierOne" varStatus="tierOneCount">
** Some Code **
<c:forEach items="${auditBudgetTierOne.auditBudgetTierTwoList}" var="auditBudgetTierTwo" varStatus="tierTwoCount">
** Some Code **
<c:forEach items="${auditBudgetTierTwo.auditBudgetItemList}" var="auditBudgetItem" varStatus="budgetItemCount">
<input type="hidden" name="tierOneIndex" value="${tierOneCount.count}">
<input type="hidden" name="tierTwoIndex" value="${tierTwoCount.count}">
<input type="hidden" name="budgetItemIndex" value="${budgetItemCount.count}">
**Element rows displayed here**
Now, when the user selects any of the element row in the inner most loop, I've to fetch the values in JS. As you can see I'm trying to get the count of each nested loop like this:
<input type="hidden" name="tierOneIndex" value="${tierOneCount.count}">
<input type="hidden" name="tierTwoIndex" value="${tierTwoCount.count}">
<input type="hidden" name="budgetItemIndex" value="${budgetItemCount.count}">
And trying to fetch the value of input field in JS as below:
var tierOneIndex = $('input[name="tierOneIndex"]').val();
var tierTwoIndex = $('input[name="tierTwoIndex"]').val();
var budgetItemIndex = $('input[name="budgetItemIndex"]').val();
But whatever element I select, I'm always getting:
tierOneIndex = 0
tierTwoIndex = 0
budgetItemIndex = 0
Any ideas how I can fetch the count values.
In your html you can do like this
<table>
<c:forEach items="${auditBudgetData.auditBudgetTierOneList}" var="auditBudgetTierOne" varStatus="tierOneCount">
** Some Code **
<c:forEach items="${auditBudgetTierOne.auditBudgetTierTwoList}" var="auditBudgetTierTwo" varStatus="tierTwoCount">
** Some Code **
<c:forEach items="${auditBudgetTierTwo.auditBudgetItemList}" var="auditBudgetItem" varStatus="budgetItemCount">
<input type="hidden" name="tierOneIndex" id="tierOneIndex_${budgetItemCount.index}" value="${tierOneCount.count}">
<input type="hidden" name="tierTwoIndex" id="tierTwoIndex_${budgetItemCount.index}" value="${tierTwoCount.count}">
<input type="hidden" name="budgetItemIndex" id ="budgetItemIndex_${budgetItemCount.index}" value="${budgetItemCount.count}">
<tr class="rows" id="${budgetItemCount.index}"><td>click Here</td></tr>
</table>
and in javascript you can do like this
$(document).ready(function(){
$("tr.rows").click(function() {
var rowid=this.id;
var tierOneIndex = $('#tierOneIndex_'+rowid).val();
var tierTwoIndex = $('#tierTwoIndex_'+rowid).val();
var budgetItemIndex = $('#budgetItemIndex_'+rowid).val();
console.log("tierOneIndex:"+tierOneIndex);
console.log("tierTwoIndex:"+tierTwoIndex);
console.log("budgetItemIndex:"+budgetItemIndex);
});
});
Note:
${tierOneCount.index} starts counting at 0
${tierOneCount.count} starts counting at 1
i created one sample fiddle also for you
http://jsfiddle.net/9CHEb/33/
Similar Approach
You will find an approach in this StackOverflow Q&A link.
Solution
In detail, I would go for something like this (JSP)
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<script src="/*link to jQuery*/"></script>
<script>
$(document).ready(function() {
$("td").click(function(event) {
var dtoItemIdx = $(this).attr("data");
//alert("Selected idx: " + dtoItemIdx);
console.info("Selected idx: " + dtoItemIdx);
});
});
</script>
<%-- Get the size of collection --%>
<c:set var="size" scope="page" value="${fn:length(dto.items)}" />
<c:out value="There are ${size} elements in the list." />
<table>
<c:forEach items="${dto.items}" var="item" varStatus="row">
<tr><td data="${row.index}">
<%-- Get the current index in the loop --%>
<c:out value="Your content i.e [row idx: ${row.index}]." />
</td></tr>
</c:forEach>
</table>
Extensions
Instead of only one loop you can obviously nest several loops. The different index could be stored in a CSV-like structrue:
...<td data="${row.index};${product.index};${properties.index}">...
Please leave a comment if this does not solve your problem.
I'm tying to bind the value to dropdownlist i.e named as subtype which is depending on another dropdownlist i.e named as type. Please tell me how I can do that.. I have given I following code which implement for binding the dropdownlist depending on another dropdownlist.
`<table>
<tr>
<td>
<label id="type">Chosen category : </label>
</td>
<td>
<% String getType=request.getParameter("id");
out.println("<h4>"+getType+" <a href='post free ads.jsp'>Change the
category</a> </h4>");
%>
</td>
</tr>
<tr>
<td>
<label id="typeselect">Select type : </label>
</td>
<td>
<select name="type">
<option value="none">Select</option>
<%
Connection conn = NewClass.getOracleConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("Select distinct company from admin.all_stuff
where stuff_type='"+getType+"' ");
while(rs.next()){
%>
<option value="<%=rs.getString(1)%>"><%=rs.getString(1)%></option>
<%
}
%>
</select>
</td>
</tr>
<tr>
<td> <label id="subtypeselect">Select Subtype : </label></td>
<td>
<select name="subtype">
<option value="none">Select</option>
<%
try
{ %>
<% String typeselected = request.getParameter("type");
Statement stmtmt = conn.createStatement();
ResultSet rse = stmtmt.executeQuery("Select model_no from admin.all_stuff
where stuff_type='"+getType+"' and company='"+typeselected+"' ");
while(rse.next()){
%>
<option value="<%=rse.getString(1)%>"><%=rse.getString(1)%></option>
<%
}
%>
<% }
catch(Exception e)
{
out.println(e.getMessage());
}
%>
}
</select>
</td>
</tr>
</table>`
You need AJAX for this to get it work.
Your jsp is compiled into a servlet and then delivered to your client. After that no more changes are possible.
You have to handle an onChange event on the first drop down box in HTML and then post an AJAX request to your server to send back the content for the second drop down box.
Easiest way to start with AJAX is to get some library for example jQuery
$.get('ajax/test.html', function(data) {
alert(data);
});
This code allow us to download from HTML page some content from URL 'ajax/test.html'.
Second argument is callback function. Variable data has content of page 'ajax/test.html'
More: http://api.jquery.com/jQuery.get/
Can someone please tell me how to set a checkbox dynamically in Javascript?
function displayResults(html){
var v = html.split(",");
document.getElementById('fsystemName').value = v[0];
if (v[1] == "true"){
document.getElementById('fUpdateActiveFlag').checked = true;
}
}
So I am passing some values from my controller separated by commas. For the checkbox, when the value is true I want it to tick the box.
EDIT:
When a value is changed from a dropdown box it calls this displayResults method as its return statement:
$('#uINewsSystemList').change(function() {
$.get("/live-application/SystemById", {systemid: $("#systemList").val()}, displayResults, "html");
I want it to update some other values such as textboxes and checkboxes. I can get the fsystemName to populate with the appropriate value but the fUpdateActiveFlag always stays unchecked.
In your question, you posted a javascript example, not JSP.
In JSP you can use a for loop to write the checkbox like this:
<% for (Element element : elementList) { %>
<input type="checkbox" name="<%=element.getName() %>" value="<%=element.getValue() %>" <%=element.getChecked() ? "checked" : "" %> />
<% } %>
Will result in:
<input type="checkbox" name="option1" value="Milk"> Milk<br>
<input type="checkbox" name="option2" value="Butter" checked> Butter<br>
<input type="checkbox" name="option3" value="Cheese"> Cheese<br>
I can`t seem to send the right entity key to servlet in my web app. I am using javascript method to submit the form with the data via a button.
The code is divide into jstl code:
<c:if test="${!empty MOFornecedorList}">
<div id="RightColumn">
<%-- Search Box --%>
<div class="searchform">
<form id="formsearch" name="formsearch" method="post" action="<c:url value='FProcurar'/>">
<span>
<input name="searchBox" class="editbox_search" id="editbox_search" size="80" maxlength="100" value="Pesquisa" type="text" />
</span>
<input name="btnsearch" class="button_search" value="Pesquisa" type="button"/>
</form>
<div class="clr"></div>
<h>Criterio de Pesquisa: </h>
<select name="Type">
<option value="1">ID</option>
<option value="2">Nome</option>
<option value="3">Email</option>
<option value="4">Fax</option>
<option value="5">Endereço</option>
</select>
</div>
<%-- END Search Box --%>
<div class="clr"></div>
<table id="ProductTable" class="detailsTable">
<tr class="header">
<th colspan="9" >Modificar Fornecedor</th>
</tr>
<tr class="tableHeading">
<td>ID</td>
<td>Nome</td>
<td>Endereço</td>
<td>Nº de Celular</td>
<td>Nº de Telefone</td>
<td>Email</td>
<td>Fax</td>
<td>Descrição</td>
<td></td>
</tr>
<c:forEach var="MOForn" items="${MOFornecedorList}" varStatus="iter">
<tr class="${'white'} tableRow">
<td>${MOForn.getFid()}</td>
<td>${MOForn.getFNome()}</td>
<td>${MOForn.getFEndereco()}</td>
<td>${MOForn.getFNCel()}</td>
<td>${MOForn.getFNTel()}</td>
<td>${MOForn.getFEmail()}</td>
<td>${MOForn.getFFax()}</td>
<td>${MOForn.getFDescricao()}</td>
<td>
<form action="<c:url value='FMOb'/>" method="post" name="FModifi">
<input type="hidden"
name="MOForn"
value="${MOForn.fid}">
<input type="button"
value="Modificar" onclick="ModF()">
</form>
</td>
</tr>
</c:forEach>
</table>
</div>
</c:if>
the javascript method
function ModF() {
jConfirm('Modificar o Fornecedor?', 'Confirmação', function(r) {
if (r == true) {
$("form[name='FModifi']").submit();
} else {
return false;
}
});
}
and the controller code:
//Check if fornecedor as been selected
int Fid = Integer.parseInt(request.getParameter("MOForn"));
//Get fornecedor object and set it to variable
Forn = transManager.getEnt(Fid,"fornecedor");
request.setAttribute("Forn",Forn);
PagesInF="FModificar";
request.setAttribute("PagesInF", PagesInF);
userPath = "/Fornecedor";
Now when i test the code the jstl will read 5 records in the item MOFornecedorList in ascending order and a button will be created in the last column.
When the button is pressed for example in the third record the JavaScript method Modf() is invoked and a confirm dialog is shown.
When the user presses the OK button the form FModifi is submitted.
Then the servlet will receive a the request to open the page FMOb where the hidden input for the button pressed will be retrieved and put in a variable type int and some other code will execute.
But the value that the form submit's is the wrong one. ex:
1 - button - MOforn = 1
2 - button - MOforn = 2
3 - button - MOforn = 3 (clicked)
4 - button - MOforn = 4
5 - button - MOforn = 5
The Form should send the value of 3 but sends the value of 5.
So please if anyone as any ideas please share.
You've multiple forms with the same name. Your JS function isn't submitting the form from which it was been called, but it is submitting the last occurrence of the form with that name in the HTML DOM tree.
You need to replace
<input type="button" value="Modificar" onclick="ModF()">
by
<input type="button" value="Modificar" onclick="confirmSubmit(this.form)">
and rewrite the function as follows:
function confirmSubmit(form) {
jConfirm('Modificar o Fornecedor?', 'Confirmação', function(confirmed) {
if (confirmed) {
form.submit();
}
}
}
I'd also suggest to use more self-documenting variable and function names like presented above, so that your code is easier understandable and maintainable in long term (not only for yourself, but also for others, for example the ones on Stackoverflow.com from who you expect an answer when you post a question...)