Reputation: 61
I am trying to get selected data from DataTable but I'm unable to retrieve the data however I was able to retrieve the row index number. Anyone can help me to get the selected row data. I will provide a working fiddle for easier work.
$(document).ready(function() {
var table = $('#example').DataTable({
'ajax': 'https://gyrocode.github.io/files/jquery-datatables/arrays_id.json',
'columnDefs': [
{
'targets': 0,
'checkboxes': {
'selectRow': true
}
}
],
'select': {
'style': 'multi'
},
'order': [[1, 'asc']]
});
// Handle form submission event
$('#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
$(form).append(
$('<input>')
.attr('type', 'hidden')
.attr('name', 'id[]')
.val(rowId)
);
});
// FOR DEMONSTRATION ONLY
// The code below is not needed in production
// Output form data to a console
$('#example-console-rows').text(rows_selected.join(","));
// Output form data to a console
$('#example-console-form').text($(form).serialize());
// Remove added elements
$('input[name="id\[\]"]', form).remove();
// Prevent actual form submission
e.preventDefault();
});
});
https://jsfiddle.net/cvinhar/82csLoy5/
Upvotes: 2
Views: 1933
Reputation: 10922
You could simply use, inside your on submit :
let selectedValues = table.rows( { selected: true } ).data();
And then loop through your values.
Upvotes: 4