Find whether check boxes are checked inside a servlet - java

I have several check box in a form I just wanna way to check whether they are checked or not .
If checked i need to store their id in the database(that i can do it ) . But my question is how to determine whether are checked or not instead of checking for each check box on at a time . I need to check whether its checked or not inside a servlet.
This is my code
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Role Id<input type="text" name="roll_id"/><br>
Role Name<input type="text" name="roll_name"/><br>
Role Description<textarea name="roll_desc"></textarea><br>
<br>
<br>
Screen1<br>
tab1<br>
<input type="checkbox" name="s1_t1_view" value="s1_t1_view" >view<br>
<input type="checkbox" name="s1_t1_add" value="s1_t1_add" >add<br>
<input type="checkbox" name="s1_t1_edit" value="s1_t1_edit" >edit<br>
<input type="checkbox" name="s1_t1_delete" value="s1_t1_delete" >delete<br>
tab2<br>
<input type="checkbox" name="s1_t2_view" value="s1_t2_view" >view<br>
<input type="checkbox" name="s1_t2_add" value="s1_t2_add" >add<br>
<input type="checkbox" name="s1_t2_edit" value="s1_t2_edit" >edit<br>
<input type="checkbox" name="s1_t2_delete" value="s1_t2_delete" >delete<br>
Screen2<br>
tab1<br>
<input type="checkbox" name="s2_t1_view" value="s2_t1_view" >view<br>
<input type="checkbox" name="s2_t1_add" value="s2_t1_add" >add<br>
<input type="checkbox" name="s2_t1_edit" value="s2_t1_edit" >edit<br>
<input type="checkbox" name="s2_t1_delete" value="s2_t1_delete" >delete<br>
tab2<br>
<input type="checkbox" name="s2_t2_view" value="s2_t2_view" >view<br>
<input type="checkbox" name="s2_t2_add" value="s2_t2_add" >add<br>
<input type="checkbox" name="s2_t2_edit" value="s2_t2_edit" >edit<br>
<input type="checkbox" name="s2_t2_delete" value="s2_t2_delete" >delete<br>
<input type="submit" name="sumbit" text="submit">
</body>
</html>
But in my code I have several check boxes . I need to hardcode that for every check box . Is there way so that i put it in a loop and check for all check boxes ?

To be simple, you can use the name attribute to get the data since you are using different name for each checkbox.
In Servlet :
String[] s1_t1_view = request.getParameterValues("s1_t1_view");
String[] s1_t1_add = request.getParameterValues("s1_t1_add");
If you want to use group of checkbox to give the user a choice between multiple values, you will need to iterate over the group in the servlet. You can use this :
In HTML : (same name = same group)
<input type = "checkbox" name = "s1_t1" value = "s1_t2_view" >View <br>
<input type = "checkbox" name = "s1_t1" value = "s1_t2_add" >Add <br>
<input type = "checkbox" name = "s1_t1" value = "s1_t2_edit" >Edit <br>
<input type = "checkbox" name = "s1_t1" value = "s1_t2_delete" >Delete<br>
In Servlet :
String[] results = request.getParameterValues("s1_t1");
for (int i = 0; i < results.length; i++) {
System.out.println(results[i]);
}

You can use
String[] checked = request.getParameterValues("checkboxName");
and then check the checked value

For me this one worked.
String[] selecttype=request.getParameterValues("selectType");
//selectType is the name of checkbox in jsp page.
This will return selected checkbox values.

Create hidden fields as
Now in your servlet as: String[] names = request.getParameterValues("checkbox");
PrintWriter pw = new PrintWriter(new File("/Desktop/sticker.txt"));
for(int i=0; i < names.length; i++) {
if(i + 1 < names.length && names[i].equals(names[i+1])) {
pw.write(names[i] + ",true\n");
++i;
} else {
pw.write(names[i]+",false\n");
}
}
pw.close();

Related

Why random checkbox choosing giving error,not in serial-wise in JSP page?

I am trying to make a basic shop-billing JSP project. now when i type random product quantity with checkbox it giving error like below image. but when i checked-value with serial wise, it is not giving the error, it giving me the result what i desiring. I have also check it is empty or not. but can't able to get out of this error. how can i get rid out of it?
Code:
<%--
Document : order
Created on : Jun 15, 2019, 3:11:06 PM
Author : Riddhi
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.sql.*" %>
<!DOCTYPE html>
<html lang="en">
<%# include file="header.jsp" %>
<h2 class="text-center"> ShopBilling </h2>
<p><br/></p>
<%
String Host = "jdbc:mysql://localhost:3306/shopbilling";
Connection connection = null;
Statement statement = null;
ResultSet rs = null;
PreparedStatement ps=null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(Host, "root", "");
StringBuilder sb = new StringBuilder();
%>
<div class="row justify-content-center">
<div class="col-md-6">
<div class="row">
<div class="col-md-6"><h3>Product Details</h3></div>
<div class="col-md-6 text-right">
Back to Home
</div>
</div>
<p></p>
<form action="" method="post">
<%
String products[] = request.getParameterValues("products");
String items[] = request.getParameterValues("item_no");
int sum=0;
if (products!= null && items!= null && products.length != 0 && items.length != 0) {
for (int i = 0; i < products.length; i++) {
%> <%
statement = connection.createStatement();
String u=request.getParameter("u");
int num=Integer.parseInt(products[i]);
String Data = "select * from products_tbl where id='"+num+"'";
rs = statement.executeQuery(Data);
while (rs.next()) {
%>
<input type="hidden" name="id" value='<%=rs.getString("id")%>'/>
<div class="form-group">
<label for="product_name">Product Name: <%=rs.getString("product_name")%></label>
<input type="hidden" class="form-control" id="product_name" name="product_name" value='<%=rs.getString("product_name")%>'>
</div>
<div class="form-group">
<label for="product_price">Product Single Price: <%=rs.getString("product_price")%></label>
<input type="hidden" class="form-control" id="product_price" name="product_price" value='<%=rs.getString("product_price")%>'>
</div>
<div class="form-group">
<label for="product_name">Item Quantity: <% out.println(items[i]); %></label>
<input type="hidden" class="form-control" id="item_no" name="item_no" value='items[j]'>
</div>
<div class="form-group">
<label for="product_name">Product Total Price: <%
int num1=Integer.parseInt(items[i]);
int propri=Integer.parseInt(rs.getString("product_price"));
out.println(num1 * propri); int gtotal= num1 * propri; %></label>
<input type="hidden" class="form-control" id="item_no" name="item_no" value='items[j]'>
</div>
<hr>
<% sum= sum + gtotal; %>
<%
}
}
}
%>
<div class="form-group">
<label for="product_name">Grand Total: <%
out.println(sum); %></label>
<input type="hidden" class="form-control" id="item_no" name="item_no" value='items[j]'>
</div>
<button type="print" onclick="window.print();" class="btn btn-warning">Print</button>
</form>
</div>
</div>
<%# include file="footer.jsp" %>
</html>
I think the problem in your code is with <input type="text" name="item_no" /> because every row in your above code has checkbox , when you submit your form only selected checkbox is passed , but all <input type="text" name="item_no" /> is passed even the null where you didn't give any value , so when you iterate you get null value with that as well .Now ,to solve this do like below :
//give value to your check-box i.e id of that row
<input type="checkbox" name="products" value ='<%=rs.getString("id")%>' />
//pass that id with your input type i.e item_no_1 ..etc
<input type="text" name='item_no_<%=rs.getString("id")%>' />
And then to get only particular value of Product Quantity where you have selected Checkbox do like below :
String products[] = request.getParameterValues("products");
if (products!= null && items!= null && products.length != 0 && items.length != 0) {
for (int i = 0; i < products.length; i++) {
//your code
<div class="form-group">
<label for="product_name">Product Total Price: <%
//getting item value of that selected checkbox
int item_no=Integer.parseInt(request.getParameter("item_no_" + products[i]));
int propri=Integer.parseInt(rs.getString("product_price"));
out.println(num1 * propri); int gtotal= num1 * propri; %></label>
<input type="hidden" class="form-control" id="item_no" name="item_no" value='items[j]'>
</div>

Accessing selected dropdown items using Java

I have a dropdown which consist the language names. I am setting the value and displaying name of the dropdown by using a hashmap.
<form action="TextTranslation" method="post" class="form" role="form" >
<div class="row">
<div id = "imageView" class="col-lg-8 center-block ">
<div class="btn-group">
<select name="country">
<%
Map<String,String> langCode = x.getCountryList();
for( Object key :langCode.keySet() )
{%>
<option value="<%=(String)key%>"><%=langCode.get(key) %> </option>
<%
System.out.println((String)key);
}
String name = request.getParameter("country");
request.setAttribute("code", name);
%>
</select>
</div>
<input type="submit" class= "btn btn-image" value="Translate">
Search Text
</div>
</div>
</form>
Values are passed correctly to dropbox as it print all the values in console. the set attribute is accessed in the particular servlet. But it gives a null value. Do you have any idea?Thank you in advance
UPDATED
<select name="country">
<%
Map<String,String> langCode = x.getCountryList();
for( Object key :langCode.keySet() )
{%>
<option value="<%=(String)key%>"><%=langCode.get(key) %> /option>
<% System.out.println((String)key);
}
String name = request.getParameter("country");
%>
</select>
<input type="hidden" name="code" value = <%= name%>/> .
In the servlet I used,
request.getParameter("code");
update your jsp likewise,
<form...>
...
<input type="hidden" name="code" value = <%= name%>/>
....
</form>
then get it from your servlet likewise,
request.getParameter("code"); // will return value of code
NOTE :
Remove from your jsp-code if above solution you gonna implement then,
request.setAttribute("code", name);

Want to display Addition result in textbox.? here is my code

addition.jsp
<form action="addition.jsp">
First Number
<input type="text" name="fno">
<br>
<br>Second Number
<input type="text" name="sno">
<br>
<br>Result
<input type="text" value="<%=Integer.parseInt(request.getParameter(" fno "))+Integer.parseInt(request.getParameter("sno ")) %>">
<br>
<br>
<input type="submit" value="ADD">
</form>
I want to display result in thrid textbox named Result on click of submit button.. i tried this code but getting error ..is there something am i missing..kindly help?
request.getParameter(" fno ") is string not a number therefore it will be a wrong format.
<%
String integer = request.getParameter("fno");
String integer1 = request.getParameter("sno");
int x = integer != null ? Integer.parseInt(integer) : 0;
int y = integer1 != null ? Integer.parseInt(integer1) : 0;
int z=x+y;
%>
<input type="text" name="integer" value="<%=z%>"/>
It can be achieved by simple java script as follow:
<html>
<body>
<form action="addition.jsp">
First Number
<input type="text" name="fno" id="fno"/>
<br>
<br>Second Number
<input type="text" name="sno" id="sno"/>
<br>
<br>Result
<input type="text" id="result"/>
<br>
<br>
<input type="button" value="ADD" onClick="setAddition();"/>
</form>
<script>
function setAddition()
{
var fno=document.getElementById("fno").value;
var sno=document.getElementById("sno").value;
document.getElementById("result").value=parseInt(fno)+parseInt(sno);
}
</script>
</body>
</html>

Validate the checkbox limit to 5

<html>
<head>
<title>HTML Checkbox</title>
</head>
<body>
enter code here
<h2> Pick your most favorite fruits: </h2>
<form name="fruitcheckbox" action="fruits.php" method="POST">
<input type="checkbox" name="fruit[]" value="orange"> Orange
<input type="checkbox" name="fruit[]" value="apple"> Apple
<input type="checkbox" name="fruit[]" value="grapefruit"> Grapefruit
<input type="checkbox" name="fruit[]" value="banana"> Banana
<input type="checkbox" name="fruit[]" value="watermelon"> Watermelon
<br>
<input type="submit" value="Save" name="btnsave">
</form>
Anyone can give me an idea how to validate this checkobox array.
if(isset($_POST['btnsave']))
{ $fruit = $_POST['fruit'];
$values = array();
foreach($chkbox as $selection )
{ if(in_array($selection, $fruit))
{ $values[ $selection ] = 1; }
else
{ $values[ $selection ] = 0; }
}
this is part of my code. I want to limit the checked checkbox to 5. Thanks. I need it badly :|
Try this. You can limit in javascript itself. So you can limit user in client side no need to go server side. It will limit you for 4 items. You can change the number in the script to increase the value
<script type="text/javascript">
function validateitem(){
var items = document.forms['fruitcheckbox'];
var inc = 0;
var i;
for (i = 0; i < items.length; i++) {
if (items[i].checked) {
inc++;
}
}
if(inc == 0) {
document.getElementById("limitmsg").innerHTML = 'Select atleast 1 item.';
return false;
} else if(inc>4){
document.getElementById("limitmsg").innerHTML = 'You can select only 4 items.';
return false;
}
}
</script>
<h2>Pick your most favorite fruits:</h2>
<form name="fruitcheckbox" action="fruits.php" method="POST"
onsubmit="return validateitem();">
<input type="checkbox" name="fruit[]" value="orange"> Orange <input
type="checkbox" name="fruit[]" value="apple"> Apple <input
type="checkbox" name="fruit[]" value="grapefruit"> Grapefruit <input
type="checkbox" name="fruit[]" value="banana"> Banana <input
type="checkbox" name="fruit[]" value="watermelon"> Watermelon <br> <span
style="color: red" id="limitmsg"></span><input type="submit"
value="Save" name="btnsave">
</form>
Do you need something like this?
if (isset($_POST['btnsave'])) {
$fruits = $_POST['fruit'];
$count = count($fruits);
if ($count > 5) {
// Error; Only 5 checks allowed
} else {
// Save the data
}
}
When you submit fields with brackets like in your example. name="fruit[]" it will be an array when it is received in the backend in php.
You could then just use this:
if(isset($_POST['fruit']) && count($_POST['fruit']) > 5) {
// add your error message
} else {
// Everything is fine as long as you dont have to select atleast one of them
}
If my understanding is not wrong you have more then 5 checkboxes and you want user to restrict to check only 5 checkboxes.
If this is the case then below code might help you.
$("input[name='fruit[]']").change(function(e) {
if($('input[name="fruit[]"]:checked').length==5) {
$("input[name='fruit[]']:not(:checked)").attr("disabled", true);
} else {
$("input[name='fruit[]']:not(:checked)").attr("disabled", false);
}
});
Above code will allow you to check only 5 check boxes, whenever user check the 5th checkbox it will disable the remaining unchecked checkboxes. whenever user uncheck any of the 5 checkboxes then it will enable all the checkboxes.

How to return an error HTML (Input Validation)

I am currently developing a web site (Part of a university assignment)
I just put some input validation, although when I redirect due to an error from validation,
For example:
var x = document.getElementById("age").checked;
var y = document.getElementById("agreement").checked;
var z = document.getElementById("sex").value;
if(x != true & y != true & z == null)
{
response.sendRedirect("Register.jsp");
}
I was looking to have some sort of error message appear above the form, to tell the user that they have created an error within the form. (For example, if they did not enter their Gender or did not agree to either of the checkboxes). Also noted, I will change the validation code slightly to be more specific to the error in which the person has made.
Form:
<h3>Register as user</h3>
<form method="POST" action="Register">
<ul>
<li>First Name: <input type="text" name ="firstName"></li>
<li>Last Name: <input type = "text" name = "lastName"></li>
<li>Email Address: <input type = "email" name = "email"></li>
<li>Gender: Male <input type ="radio" name ="sex" value="male">
Female <input type ="radio" name ="sex" value="female"></li>
<li>User Name <input type="text" name="username"></li>
<li>Password <input type="password" name="password"></li>
<li>You must be 12 or over to register to this web site. Please check if you are over 12: <input type = "checkbox" name="age"></li>
<li>Please check this box to agree to the Terms and Conditions <input type ="checkbox" name="agreement"></li>
</ul>
<br/>
<input type="submit" value="Register">
</form>
Thank you for any help or advice you can give me, I really appreciate it as I am rather new to web development and I want to improve and understand techniques that web developers use.
var validate = function(form) {
var errors = [];
if (!form.sex[0].checked && !form.sex[1].checked) {
errors.push('Please select a gender');
}
if (!form.agreement.checked) {
errors.push('Please agree to T&C');
}
if (errors.length) {
alert(errors.join('\n'));
return false;
}
return true;
};
<h3>Register as user</h3>
<form method="POST" action="Register.jsp" onsubmit="return validate(this);">
<ul>
<li>First Name:
<input type="text" name="firstName">
</li>
<li>Last Name:
<input type="text" name="lastName">
</li>
<li>Email Address:
<input type="email" name="email">
</li>
<li>Gender: Male
<input type="radio" name="sex" value="male">Female
<input type="radio" name="sex" value="female">
</li>
<li>User Name
<input type="text" name="username">
</li>
<li>Password
<input type="password" name="password">
</li>
<li>You must be 12 or over to register to this web site. Please check if you are over 12:
<input type="checkbox" name="age">
</li>
<li>Please check this box to agree to the Terms and Conditions
<input type="checkbox" name="agreement">
</li>
</ul>
<br/>
<input type="submit" value="Register">
</form>
I did something like this. I have an html element which is hidden by default.
It is red and take the whole width of the div I put into.
And I've a function to manage errors :
var manageError = function(message) {
$("#element").val(message); // or $("#element").html(message) I guess
$("#element").clearQueue();
$("#element")slideDown(200).delay(10000).slideUp(200);
};
Does it help ?
use jQuery to do this. since you are learning..it will be more helpful for you.
first thing I noticed there, you have used response.sendRedirect(...); in side your javascript which is a wrong approach.
And in your form, don't use un-ordered list like approach, simply use div tags.
I will give a simple example:
<h3>Register as user</h3>
<form method="POST" action="Register.jsp" id="formId">
First Name:
<input type="text" name="firstName">Last Name:
<input type="text" name="lastName">
<div id="errMsg"></div>
<input type="button" value="submit" id="submtBtn">
</form>
and in your javascript file, use it with jQuery:
< !DOCTYPE html >
< html >
< head >
< script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" > < /script>
</head >
< script >
$("submtBtn").click(function({
var errorMsg = "";
if ($("firstName").val === '' || $("lastName").val === '') {
errorMsg = "<b>firstName and LastName can not be empty!<b>";
$("errMsg").html(errMsg);
return;
}
$("#formId").submit();
});
< /script>
you can follow above approach.... if you're using Servlets, you could follow jQuery Ajax to submit your values. try and see...hope it will give you an idea..!
First put the validation code in a function and call that function.
function validate(){
..........write your validation code
}
Call this from submit button via onclick or onchange or onblur attribute of input tag.
You can always use HTML 5. With the required action. They can never leave anything blank if this is in. Be aware that it might work with a space in it or something.
Try this:
<li>First Name: <input type="text" name ="firstName" required></li>

Categories