Skip to content Skip to sidebar Skip to footer

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('

Solution 1:

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

Solution 2:

You can get it by

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

Solution 3:

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

Post a Comment for "Getting Checkbox Value(s) From A Servlet"