Getting checkboxes check state - java

I am trying to get the check boxes' check state with the code below but ended up with the following error if the any of the checkboxes are not checked. My goal is to update the database table with the checkbox state. if checked then 1 else 0.
Error:
Severe: java.lang.NullPointerException
at doPost(Controller.java:125)
java:
String[] chkDisperse = request.getParameterValues("chkDisperse");
int status;
for (int i = 0; i < attId.length; i++) {
if (chkDisperse[i] == null) {
//(line 25 here)
status = 0;
}
else
{
status = 1;
}
html:
<c:forEach var="AttList" items="${att}" varStatus="iter">
<tr id="test">
<td style="text-align: center;"><input name="attId" type="hidden" value="${AttList.attId}" /></td>
<td style="text-align: center;"><input type="checkbox" name="chkDisperse" value="${AttList.isPresentDisperse}" ${AttList.isPresentDisperse == 1 ? 'checked' : ''}></td>
</tr>
</c:forEach>

It seems that selected checkbox values are not being passed to the servlet. Hence you get array as null here,
String[] chkDisperse = request.getParameterValues("chkDisperse");.
And you end up with NPE at this line:
if (chkDisperse[i] == null)
Make sure that the checkbox are properly enclosed within the form tag. In case it is an ajax call do check the parameters being sent from the web browser console.
Edited
I want to set the the status to 0 if not checked
In jsp or js file imported in jsp, try this jQuery solution:
$(function() { //dom ready
$('input[name=chkDisperse]').on('change', function() {//change event handler
this.value = this.checked ? '1' : '0';
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="checkbox" name="chkDisperse" value="0" />
<input type="checkbox" name="chkDisperse" value="1" />
This is plain js solution:
var putState = function(input) {
input.value = input.checked ? '1' : '0';
};
<input type="checkbox" name="chkDisperse" value="0" onchange='putState(this);' />
<input type="checkbox" name="chkDisperse" value="1" onchange='putState(this);' />

Related

How can I get disabled from input tag?

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 {
//...
}
}

How to select mutiple checkboxes using selenium webdriver reading data from excel?

I am using Coded UI for creating some test cases for a web application, while doing the same I have encountered an issue. The page contains 3 tables with mutiple check boxes, I am not able to click on checkboxes reading data from excel.Someone help me to find a solution
Here is my html code:
Table 1 - HTML:
<table id="ContentPlaceHolder1_ctl04_cbl_CCPEC01_01">
<tbody>
<tr>
<td>
<input
id="ContentPlaceHolder1_ctl04_cbl_CCPEC01_01_0"
type="checkbox"
name="ctl00$ContentPlaceHolder1$ctl04$cbl_CCPEC01_01$0"
value=" Ambu-bag ">
<label for="ContentPlaceHolder1_ctl04_cbl_CCPEC01_01_0"> Ambu-bag </label>
</td>
<td>
<input
id="ContentPlaceHolder1_ctl04_cbl_CCPEC01_01_1"
type="checkbox"
name="ctl00$ContentPlaceHolder1$ctl04$cbl_CCPEC01_01$1"
value=" apnea monitor ">
<label
for="ContentPlaceHolder1_ctl04_cbl_CCPEC01_01_1"> apnea monitor </label>
</td>
<td>
</tr>
</tbody>
</table>
Table 2 - HTML:
<table id="ContentPlaceHolder1_ctl04_cbl_CCPOP01_01">
//table 2
<tbody>
<tr>
<td><input id="ContentPlaceHolder1_ctl04_cbl_CCPOP01_01_0"
type="checkbox" name="ctl00$ContentPlaceHolder1$ctl04$cbl_CCPOP01_01$0"
value=" Universal ">
<label for="ContentPlaceHolder1_ctl04_cbl_CCPOP01_01_0"> Universal </label>
</td>
<td>
<input id="ContentPlaceHolder1_ctl04_cbl_CCPOP01_01_1"
type="checkbox"
name="ctl00$ContentPlaceHolder1$ctl04$cbl_CCPOP01_01$1" value=" Aspiration ">
<label for="ContentPlaceHolder1_ctl04_cbl_CCPOP01_01_1"> Aspiration </label>
</tr>
</tbody>
</table>
Here is my sample code.But not working fine.
Table 1 - Code:
String valueEquipmentChecklist = data.getEquipmentChecklist().get(rowCnt);//data reading from excel
List<WebElement> equipChecklist = driver.findElements(By.xpath("//input[#type='checkbox']"));
List<String> equipmentChecklistList = new ArrayList<String>(Arrays.asList(valueEquipmentChecklist.split(",")));
for (String equipmentChecklistCheck : equipmentChecklistList) {
for (WebElement equipmentChecklistChk : equipChecklist) {
if (equipmentChecklistChk.getAttribute("value").equalsIgnoreCase(equipmentChecklistCheck)) {
if (!equipmentChecklistChk.isSelected()) {
equipmentChecklistChk.click();
}
}
}
}
Table 2 - Code:
String valueOngoingPrecuations = data.getOngoingPrecuations().get(rowCnt);
List<WebElement> ongoingPrecuations = driver.findElements(By.xpath("//input[#type='checkbox']"));
List<String> ongoingPrecuationsList = new ArrayList<String>(Arrays.asList(valueOngoingPrecuations.split(",")));
for (String ongoingPrecuationsCheck : ongoingPrecuationsList) {
for (WebElement ongoingPrecuationsChk : ongoingPrecuations) {
if (ongoingPrecuationsChk.getAttribute("value").equalsIgnoreCase(ongoingPrecuationsCheck)) {
if (!ongoingPrecuationsChk.isSelected()) {
ongoingPrecuationsChk.click();
}
}
}
}
accoring to HTML you provided value of checkboxes contains spaces, possibly in your excel file this spaces are not exist, so you should delete spaces in value of checkbox before comparing or use "contains" instead of "equals"

Conditional Statements II

Those are the fields that I have that I want to write a conditional statement for in a PDF form that I am creating in Adobe Acrobat Pro X. In the form if I tick the checkbox I would like FP1 to get the value from QxHxW1. If the checkbox is not ticked I want FP1 to register as "0". I have been trying to do this with different tutorials that I have found online and each time I get some sort of SyntaxError.
is there anything I can do to fix this? Am I way off with the way that this is written?
FrenchPane1 is a checkbox
FP1 is a text box
QxHxW1 is a text box
Using javascript, this would be:
var check = document.getElementsByClassName('check');
for( var i = 0; i < check.length; i++ ){
check[i].onchange = function() {
var isChecked = this.checked;
var target = document.querySelector(this.dataset.target);
var source = document.querySelector(this.dataset.source);
target.value = isChecked ? source.value : '0';
}
}
<div>
<label for="FrenchPane1"><input type="checkbox" id="FrenchPane1" data-target="#FP1" data-source="#QxHxW1" class="check"> FrenchPane1</label>
<input type="text" name="FP1" id="FP1">
<input type="text" name="QxHxW1" id="QxHxW1" value="Some values">
</div>
<div>
<label for="FrenchPane1"><input type="checkbox" id="FrenchPane2" data-target="#FP2" data-source="#QxHxW2" class="check"> FrenchPane1</label>
<input type="text" name="FP2" id="FP2">
<input type="text" name="QxHxW2" id="QxHxW2" value="Some values 2">
</div>

Working with Java beans and Servlet values dynamically

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/>

Java Get ALL elements from a multiselect Box

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.

Categories

Resources