I have a servlet with MySQL database in it. It looks like this:
here is the piece of code for it:
out.println("<table id = \"main_section\" cellspacing=\"1\" bgcolor=\"red\" > ");
out.println ("<tr> ");
out.println("<td >NUMBER</td>");
out.println("<td >PAYMENT</td>");
out.println("<td >RECEIVER</td>");
out.println("<td >VALUE </td>");
out.println("<td >CHECKBOX</td>");
out.println("</tr>");
out.println("<tr>");
for (int i = 0; i < ex.getExpenses().size(); i++) {
out.println("<td > " + ex.getExpenses().get(i) + "</td>");
if (i>0 && (i+1)%4==0) {
out.println("<td><input type=\"checkbox\" name=\"checkbox\"></td>");
out.println("</tr><tr>");
}
}
out.println("</tr>");
What I need to do is to create a submit button that calculates the sum of VALUE of the checked boxes. for instance, if NUMBER 1 and 2 are checked the submit button should give the result of 5577.0 (VALUE 22.0+5555.0). Can anyone please help me with that?
You will need to do request. getParameter("approver") if you get the value as null then its unchecked, else its checked if you get the valid value. Whenever we submit checkbox without checking request.
String checked = request. getParameterValue("checkboxName"); String[] checkedValues = request. getParameterValues("checkboxName");
First of all, you should learn about JSPs and generate your HTML markup from a JSP rather than from the servlet.
Now for your problem. Each of these rows comes from a database table. So each of these rows should have an ID (primary key). Assign the ID of the row to the value of the checkbox. When you submit your form, the servlet will receive all the IDs of the checked checkboxes. Get the values corresponding from these IDs from the database, and sum them (or execute a query that computes the sum directly):
<input type="checkbox" name="checkedRows" value="${idOfCurrentRow}">
In the servlet handling the form submission:
String[] checkedIds = request.getParameterValues("checkedRows");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With