Set a checkbox in Javascript dynamically - java

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>

Related

How to send dropdown value to servlet NOT the option text

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

Multiple checkbox checked value

I have written the following code in JSFiddle to able so get the sum of combined values of the checkboxes.
Script
var inputs = document.getElementsByClassName('sum'),
total = document.getElementById('payment-total');
for (var i=0; i < inputs.length; i++) {
inputs[i].onchange = function() {
var add = this.value * (this.checked ? 1 : -1);
total.innerHTML = parseFloat(total.innerHTML) + add
}
}
Code
<input value="33" type="checkbox" class="sum" data-toggle="checkbox">
<input value="50" type="checkbox" class="sum" data-toggle="checkbox">
<input value="62" type="checkbox" class="sum" data-toggle="checkbox">
<span id="payment-total">0</span>
There it works perfect, when I implement this in my system there is no reslut or any error.
The checkboxes in my system are genarated by an MySQL output.
Any suggestions what migh be wrong?
Your code is probably running before the elements are dynamically generated, so the event handlers are not being attached. Try delegating the event handlers using .on() method:
$total = $('#payment-total');
$(document).on("click", ".sum", function() {
var add = this.value * (this.checked ? 1 : -1);
$total.text(function(i, value) {
return parseFloat(value) + add;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input value="33" type="checkbox" class="sum" data-toggle="checkbox">
<input value="50" type="checkbox" class="sum" data-toggle="checkbox">
<input value="62" type="checkbox" class="sum" data-toggle="checkbox">
<span id="payment-total">0</span>
I prefer to use pure javascript for your solution because you didn't use Jquery on your code. I think problem reason comes from Javascript eventListener. When you create a new element to your document, you should add its events.
In first code i create a checkbox but this is not work as others. link_1
<http://jsfiddle.net/3oweu107/1/>
However in second code i add event as other checkbox so payment-total value calculation done by new event. link_2
<http://jsfiddle.net/3oweu107/2/>
i hope this will help your problem :)

error submitting multiple checkboxes

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.

How to use JCheckBox to number/name check boxes in a collection i.e. key1, key2, etc

In a servlet I have this
while (result.next()) {
JCheckBox key = new JCheckBox(); *new statement I'm thinking to add in
key.setSelected(false); *new statement I'm thinking to add in
resultsArray[rowcount][0] = result.getString(1); This is the actual value of key
resultsArray[rowcount][1] = result.getString(2);
.
.
.
end
do ...
search_results.add(resultsArray[row][col])
end
helps to fill up the string array and...
session.setAttribute("searchresults",search_results);
So that I can process it in the jsp
I populate resultsArray with the results of a query.
results.getString(1) will always have the key value of the record in the table of the database searched.
I list the results of my search from the jsp with
td align=left valign=top>
input type="checkbox" name="key" value=<%=resultsArray.get(pos + 0)%>/>
/td>
The page lists the results you searched for (with a checkbox) and you now check off the records you really want to delete. I will then come back with that smaller list of information and ask you to "check off one more time if you are sure you want to delete these records".
The problem is I while name="key<%=i%> might very well display key1, key2, key3, etc in the jsp. In the servlet I am not sure how to make
JCheckBox keyN = new JCheckBox();
happen. Any and all suggestions are appreciated, thanks.
Nelson
I was being overly complicated. All that I had to do was to process the posted argument. to be able to redisplay the choices that were selected on the previous page. I didn't need JCheckBox at all for any of this.
String onoff = request.getParameter(Keyvalue);
%>
<% if ((onoff == null) || (onoff.equals(""))) { %>
<input type="checkbox" name=<%=Keyvalue%> />
<% } else {
if (onoff.equals("off")) { %>
<input type="checkbox" name=<%=Keyvalue%> />
<% } else { %>
<input type="checkbox" name=<%=Keyvalue%> checked />
<% }} %>

How to get index of nested JSTL c:forEach from JSP to JS

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.

Categories

Resources