get value of checboxes from action - java

I have list checkboxes in jsp, now I just want to get value of some checkboxes have checked.
<%
for(DictItem dictItemDomain : dictItemDomains) {
%>
<aui:input
name="businessDomains"
id='<%= "businessDomain" + dictItemDomain.getDictItemId()%>'
value="<%=dictItemDomain.getItemCode() %>"
type="checkbox"
label="<%=dictItemDomain.getItemName(locale, true)%>"/>
<%
}
%>
controller :
String[] domains =
ParamUtil.getParameterValues(
actionRequest, "businessDomains");
but domains contain value of checked and unchecked together

<aui:input name="listBussinessDomains" type="hidden" value="" />
<%
for(DictItem dictItemDomain : dictItemDomains) {
%>
<aui:input
name="businessDomains"
id='<%= "businessDomain" + dictItemDomain.getDictItemId()%>'
value="<%=dictItemDomain.getItemCode() %>"
type="checkbox"
label="<%=dictItemDomain.getItemName(locale, true)%>"
cssClass="getval"
/>
<%
}
%>
I try to add hidden input and using jquery to make an Array value then I put it for value attr of hidden input, finally, retrieve in action controller.
<script>
AUI().ready(function(A) {
var businessTypeCbs = $(".getval");
var businessTypeCbsChecked = $(".getval:checked");
var checkedArr = [];
var listBussinessDomains = A.one("#<portlet:namespace />listBussinessDomains");
businessTypeCbsChecked.each(function() {
checkedArr.push($(this).attr("value"));
listBussinessDomains.val(checkedArr);
});
businessTypeCbs.click(function() {
if($(this).is(":checked")) {
//alert($(this).attr("value") + ' ' + $(this).attr("id"));
if($.inArray($(this).attr("value"), checkedArr) == -1) {
checkedArr.push($(this).attr("value"));
}
} else {
if($.inArray($(this).attr("value"), checkedArr) > -1) {
removeItem = $(this).attr("value");
checkedArr = $.grep(checkedArr, function(value) {
return value != removeItem;
});
}
}
listBussinessDomains.val(checkedArr);
});
});
in controller
String [] listBussinessDomains = ParamUtil
.getParameterValues(actionRequest, "listBussinessDomains");
WORKED!

Related

How do I update a multiple row with checkbox

I want to update a particular column in my database with the word 'trash' but I need to first tick the values in check box. Then when u tick the checkbox, the system will only update the status field of the id's selected
public void updateNow(Messages message){
Query query = em.createNativeQuery("Update Messages set status = 'trash' WHERE id =:id");
query.setParameter("id", message.getId());
query.executeUpdate();
}
}
<%
//updating the filed
String[] arr = request.getParameterValues("content");
int sum=0;
if(request.getParameter("update")!=null){
try{
for (int i=0; i<arr.length; i++){
sl.updateNow(arr[i]);
sum++;
msg = "<script>alert('You have move message to trash')</script>";
}
}catch (Exception e){
msg="Please Do select an email before performing an action" + e.getMessage();
e.printStackTrace();
}
}
%>
<html>
<body>
<form action="" method="post">
<%
List inboxFetch = sl.allMessages(user, "inbox");
Iterator inboxIterate = inboxFetch.iterator();
while(inboxIterate.hasNext()){
Messages all = (Messages) inboxIterate.next();
%>
<input type="checkbox" value="<%=all.getId() %>" name="content">
<%
}
%>
<br />
<hr />
<button type="submit" name="update" class="btn btn-sm btn-danger">Update</button>
</form>
</body>
</html>
Please how do I achieve this? I have been on this code now for quite some hours seems I can't get through it

How to find attribute without value is present or not in HTML tag using Selenium?

Ex: Radio - checked
<input id="rdo" type="radio" name="nrdo" value="1" checked>
Ex: Radio - unchecked
<input id="rdo" type="radio" name="nrdo" value="1">
Need to find attribute without value is present on HTML tag or not using Selenium.
This code works only if attribute has value:
public boolean isAttribtuePresent(String element, String attribute) {
Boolean result = false;
String value = "vvv";
// element = "Month ''May'' #xpath=//button[text()='Jun']";
try {
value = webElement.getAttribute(attribute);
if (value != null) {
result = true;
}
} catch (Exception e) {
System.out.print(e.toString());
}
System.out.print("***"+value+"*****");
return result;
}
Just check if attributre value is not null.
const hasAttr = (el, attr) => el.getAttribute(attr) != null
console.log(hasAttr(rdo, 'checked'))
console.log(hasAttr(rdo2, 'checked'))
<input id="rdo" type="radio" name="nrdo" value="1" checked>
<input id="rdo2" type="radio" name="nrdo" value="1">
The element.getAttribute(attributeName) returns null for both
1. Attribute without value
2. Attribute is not present
Use Jquery attr
http://api.jquery.com/attr/
$.each($( ":input" ),function(i,o){
alert($(this).attr("value")==undefined);
})

Number Format Exception JSP Page with cookies

I wrote this small code for handling cookies.However,when i click on the "next" button it throws a
java.lang.NumberFormatException: For input string: "current"
Code:
<%#page import="java.util.*"%>
<%
int current=0;
Cookie[] cookies = request.getCookies();
Cookie cookie = null;
if(cookies != null){
for(int i=0;i<cookies.length;i++){
if(cookies[i].getName().equals("last"))
cookie = cookies[i];
}
}
if(cookie != null){
String btn = request.getParameter("button");
if(btn != null){
if(btn.equals("next"))
current = Integer.parseInt(cookie.getValue()) + 1;
else
current = Integer.parseInt(cookie.getValue()) - 1;
}
}
response.addCookie(new Cookie("last",String.valueOf("current")));
out.println(current);
%>
<html>
<head>
</head>
<body>
<form method="post">
<input type="submit" name="button" value="prev" />
<input type="submit" name="button" value="next" />
</form>
</body>
</html>
You set the cookie to value "current"
String.valueOf("current")
but you want
String.valueOf(current)

How to send variable in action java class to jquery?

When I click on the button will be equal to the amount of undefind while the amount is equal to 1
in jsp page :
<%
String err1 = (String) request.getAttribute("err2");
int code = 0;
if (err1 != null){
code = Integer.parseInt(err1);
System.out.println(" code " + code);
}
%>
<button type="button" id="btnok">ok</button>
<br />
<%if(code == 3){ %>
<input id="txtcode" type="hidden" value="1" />
<%}%>
<br />
in jquery code:
$(document).ready(function() {
$("#btnok").click(function(event) {
var xxx = $("#txtcode").val();
alert("xxx 1 test + " + xxx);
});
});
The most likely reason is that the condition:
<%if(code == 3){ %>
<input id="txtcode" type="hidden" value="1" />
<%}%>
is not being met and the input is not being inserted to the DOM. Reload the page and view the page source to see if the input is inserted.

JSON.stringify(array) from jsp to servlet (loop using javax.json-api1.0. jar or javax.json-1.0.jar only)

HTML :
<table>
<tr>
<td>
<input type="hidden" value="flag1" />
</td>
<td>
<input type="text" value="orange" />
</td>
<td>
<input type="text" value="1.00" />
</td>
<td>
<input type="text" value="5" />
</td>
</tr>
<tr>
<td>
<input type="hidden" value="flag2" />
</td>
<td>
<input type="text" value="apple" />
</td>
<td>
<input type="text" value="2.00" />
</td>
<td>
<input type="text" value="5" />
</td>
</tr>
</table>
JS :
var array = $.map($('table tr'), function (val, i) {
var obj = {}, inputs = $(val).find('td input:not(:hidden)');
obj[inputs.filter(':first').val()] = $.map(inputs.not(':first'), function (val, i) {
return val.value;
});
return obj;
});
alert(JSON.stringify(array));
$(document).on("click","#save",function(){
$.post("servlet.html","data="+JSON.stringify(array)+"",function(response){
});
});
Java servlet contains this :
String data = request.getParameter("data");
data looks like this :
[{"flag1":["orange","1.00","5"]},{"flag2":["apple","2.00","5"]}]//this is get from table row data using stringify
i want to get on first loop using javax.json-api1.0.jar or javax.json-1.0.jar only :
on first loop :
flag1
Orange
1.00
5
on second loop :
flag2
Apple
2.00
5
Any help will be best.
You can do it with only json-api, but you must be sure of the structure of the input data.
If not, gson or jackson2 are easier to use.
If you want to use json-api, you could do something like :
First declare a JsonFactoryReader attribute in your servlet because you will create a reader per request.
JsonReaderFactory readerFactory = Json.createReaderFactory(null);
then in your service or doXXX method do :
String data = request.getParameter("data");
// create a reader for json data
JsonReader jr = readerFactory.createReader(new StringReader(data));
// tol level must be an array, and we count the iteration for eventual error messages
JsonArray ja = jr.readArray();
int iteration = 0;
for (JsonValue jv: ja) {
// sub elements must be dicts
if (jv.getValueType() != ValueType.OBJECT) {
throw new FormatException(iteration, jv);
}
for (Entry<String, JsonValue> e: ((JsonObject) jv).entrySet()) {
// the key
String key = e.getKey();
if (e.getValue().getValueType() != ValueType.ARRAY) {
throw new FormatException(iteration, e.getValue());
}
// the values, first is a string
JsonArray array = (JsonArray) e.getValue();
for (int i=0; i<array.size(); i++) {
System.out.println(array.get(0).getValueType());
}
String name = array.getString(0);
// next a float and an int
float fval;
int ival;
try {
fval = Float.valueOf(array.getString(1));
ival = Integer.valueOf(array.getString(2));
}
catch (NumberFormatException ex) {
throw new FormatException(iteration, array);
}
// Do your stuff with those values ...
// for instance Data data = new Data(key, name, fval, ival) ...
iteration++;
}
}
I propose you an exception class to handle format errors (at least you know why it breaked ...):
class FormatException extends ServletException {
FormatException(int i, JsonValue jv) {
super("Iteration " + String.valueOf(i) + " : " + jv.toString());
}
}

Categories