简体   繁体   中英

Getting checkbox value(s) from a Servlet

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?

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");

你可以得到它

String[] values = req.getParameterValues("checkbox");

Change this line:

 out.println("<td><input type=\\"checkbox\\" name=\\"checkbox\\"></td>"); 

To read:

out.println("<td><input type=\"checkbox\" name=\"selected\" value=\""+ex.getExpenses().get(i-1)+"\"></td>");

This will create checkboxes that you can identify themselves by the value-tag. I hope that the "number" field is a primary key or the like.

Then on next run. You can get all checked values by:

String[] selected = request.getParameters("selected");

now, you can just add up the numbers. I don't quite understand how you Expenses-list looks like from the code. Here is just an illustration that will not work but could give you the idea on how to do it:

int sum = 0;
for (int i = 0; i < ex.getExpenses().size(); i++)
  for(int selectedIndex = 0; selectedIndex < selected.length; ++selectedIndex)
    if (ex.getExpenses().get(i) == Integer.parseInt(selected[selectedIndex]))
      sum += ex.getExpenses().get(i-1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM