Reputation: 121
I'm new to datatables and have implemented checkbox's in each row of data table. I have followed this sample for this.
I just want to return only selected row's data, but instead it returns all data on form submit action.
Here's screenshot
In screenshot above, I have only selected second and third row, but table.column(0).checkboxes.selected() returns all rows.
Javascript Code
var paramedics;
table;
var i = 0;
$(document).ready(function () {
table = $("#example").DataTable({
"ajax": {
"url": "/Home/GetCaseAllocations",
"type": "GET",
"datatype": "json",
},
"select": {
"style": "multi"
},
"order": [[1, "asc"]],
"columns": [
{
"data": null,
'targets': 0,
'checkboxes': {
'selectRow': true
}
},
{ "data": "patientId" },
{ "data": "name" },
{ "data": "age" },
{ "data": "zipCode" },
{ "data": "status" },
{ "data": "currentAllocation" },
{
"data": "paramedicsAvailable", width: "200px",
render: function (data, type, row) {
var $select = $("<select></select>",
{
id: "allocation" + i
});
$.each(data, function (k, v) {
var $option = $("<option></option>",
{
text: v,
value: k
});
if (row.owner === v) {
$option.attr("selected", "selected")
}
$select.append($option);
});
return $select.prop("outerHTML");
i++;
}
},
],
});
$("#frm-example").on('submit', function (e) {
var form = this;
var rows_selected = table.column(0).checkboxes.selected();
// Iterate over all selected checkboxes
$.each(rows_selected, function (index, rowId) {
// Create a hidden element
console.log(table.row(index));
$(form).append(
$('<input>')
.attr('type', 'hidden')
.attr('name', 'id[]')
.val(rowId)
);
});
});
});
Upvotes: 0
Views: 5009
Reputation: 58880
One of the current limitation of the jQuery DataTables Checkboxes plug-in is that column containing checkboxes must have unique data.
Use columns.data
option to define data property in your response containing unique data. For example:
"columns": [
{
"data": "patientId",
'targets': 0,
'checkboxes': {
'selectRow': true
}
},
// ... skipped ...
],
Upvotes: 2
Reputation: 147
Check the following
// Get the selected
var row = $("#example").column(0).checkboxes.selected();
// Create variable for the ids array
var selected_items = [];
// Loop through to get the selected id
$.each(row, function(index, rowId){
//this add selected ID as object into array
selected_items.push({id:rowId});
});
Upvotes: 1