Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting checkbox value(s) from a Servlet

I have a servlet with MySQL database in it. It looks like this: enter image description here

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?

like image 634
Gipsy Avatar asked May 18 '12 19:05

Gipsy


People also ask

How check checkbox is checked or not in servlet?

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.

How can I get multiple checkbox values in JSP?

String checked = request. getParameterValue("checkboxName"); String[] checkedValues = request. getParameterValues("checkboxName");


1 Answers

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");
like image 121
JB Nizet Avatar answered Oct 07 '22 16:10

JB Nizet