QuestionMarks QuestionMarks - 1 year ago 34
Java Question

How to iterate through selected HTML table rows and retrieve data from each row

I am displaying a list of data selected from an Oracle database on a jsp using Spring MVC.

The code for displaying the data in a table is as follows (using datatables plugin):

"bProcessing" : false, "bServerSide" : false, "responsive" : true, "sort" : "position", "oLanguage" :
"sEmptyTable" : "There were no matches found for the search. Try again with different criteria. "
"sAjaxSource" : "addLocations.htm",
"responsive": "true",
"order": [[0, "asc"]],
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
iDisplayLength: -1,
"scrollY": "200px",
"scrollCollapse": true,
"paging": false,

"sAjaxDataProp" : "locationData", "bDestroy" : true,
"aoColumns" :
{"mData" : "id"},
{"mData" : "id"}
'columnDefs' : [{
'targets' : 0,
'className': 'dt-body-center',
'render': function (data, type, full, meta){
return '<input type="checkbox" name="selectedID" value="' + $('<div/>').text(data).html() + '">';

This works to assign a checkbox to each row, and assigns the checkbox with the value of the id. In my controller, I am able to test with the following code, which returns the value of the first selected checkbox:

@RequestMapping(params="saveLocations", method = RequestMethod.POST)
public String saveLocations(HttpServletRequest req){
return "redirect:/locations.htm";

On the jsp, this submit is handled using a basic submit button:

<button type="submit" class="btn btn-primary" id="saveLocations" name="saveLocations">Save</button>

What I am trying to do is retrieve each selected row in the table. I know that I have to loop through the values somehow, but I'm not really sure how to do that.

ANSWER: When returning multiple values, you need to use getParameterValues(). So the new controller looks like this:

String[] values = req.getParameterValues("selectedID");
for(int i=0;i<values.length;i++)

Answer Source


You can use the snippet below, where frm-example is ID of your form.

It will iterate over all checkboxes in the table and add those not present in DOM as <input type="hidden"> elements.

// Handle form submission event
$('#frm-example').on('submit', function(e){
   var form = this;

   // Iterate over all checkboxes in the table
      // If checkbox doesn't exist in DOM
      if(!$.contains(document, this)){
         // If checkbox is checked
            // Create a hidden element 
                  .attr('type', 'hidden')

I'm not Java expert but it looks like you need to use getParameterValues() on the server-side instead of getParameter(). According to the manual getParameter() should be used when there is only one value.


See jQuery DataTables: How to submit all pages form data for more details and demonstration.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download