Reputation: 246
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):
$("#addLocationsTable").DataTable({
"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,
'searchable':false,
'orderable':false,
'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){
System.out.println(req.getParameter("selectedID"));
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++)
{
System.out.println(values[i]);
}
Upvotes: 3
Views: 1684
Reputation: 58890
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
table.$('input[type="checkbox"]').each(function(){
// If checkbox doesn't exist in DOM
if(!$.contains(document, this)){
// If checkbox is checked
if(this.checked){
// Create a hidden element
$(form).append(
$('<input>')
.attr('type', 'hidden')
.attr('name', this.name)
.val(this.value)
);
}
}
});
});
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.
Upvotes: 2