Get Multiple Selected Row html data out of Datatables - javascript

I am using Datatables (datatables.net) successfully to display all the data I need. But I am having difficulty understanding how to pull out selected column data from a json object. I have failed to JSON.stringify the object, as well as attempt to access the properties of the object directly.
The use of the datatables allows the user to select multiple rows and a built in button will perform a submit action to my rails server. I currently cannot access the object to parse the data. I may need a loop and thats fine, but again, I am having difficulty understanding the library on multiple select.
I have successfully console.log the object and verified the data I want is present. I currently want the 1 index of Array[12] for n selected rows. I have figured out how to provide a count of the selected rows, so I can parse the object using the count as a loop limiter. But again my attempts have failed.
Console.log object:
[Array[12], Array[12], Array[12], context: Array[1], selector: Object, ajax: Object, colReorder: Object, keys: Object]
0:Array[12]0:""1:"36"2:
Code:
$(document).ready(function() {
$('.stay').DataTable( {
dom: "<'row'<'col-sm-8'B><'col-sm-4'f>>"+ 'rt' + "<'row'<'col-sm-6'i><'col-sm-6'p>>",
buttons: [
'selectNone',
'selectAll',
{
extend: 'selected',
text: 'Assign Rooms',
action: function ( e, dt, node, config ) {
var rows = dt.rows( { selected: true } ).count();
var selected_rows = dt.rows( {selected: true} ).data(0);
console.log(selected_rows);
url = window.location;
// index = url.indexOf("housekeeper")
// alert(index);
alert( 'There are '+rows+'(s) selected in the table' );
alert(selected_rows[0])
// $.ajax({
// url: "/BookCreate/?mdate="+mdate+"&phone="+phone,
// type: "post",
// data: values,
// success: function(){
// alert('Saved Successfully');
// },
// error:function(){
// alert('Error');
// }
// });
}
},
{
extend: 'colvis',
text: 'Columns',
autoClose: true,
},
{
extend: 'copy',
text: '<i class="fa fa-files-o"></i>',
exportOptions: {
columns: ':visible'
}
},
{
extend: 'excel',
text: '<i class="fa fa-file-excel-o"></i>',
exportOptions: {
columns: ':visible'
}
},
{
extend: 'csv',
text: '<i class="fa fa-file-code-o"></i>',
exportOptions: {
columns: ':visible'
}
},
{
extend: 'pdf',
text: '<i class="fa fa-file-pdf-o"></i>',
exportOptions: {
columns: ':visible'
}
},
{
extend: 'print',
text: '<i class="fa fa-print"></i>',
exportOptions: {
columns: ':visible'
}
},
],
columnDefs: [ {
visible: false
} ],
columnDefs: [ {
orderable: false,
className: 'select-checkbox',
targets: 0
} ],
select: {
style: 'os',
selector: 'td:first-child',
style: 'multi'
},
order: [[ 2, 'asc' ]]
} ).on( 'buttons-action', function ( e, buttonApi, dataTable, node, config ) {
// action put here
console.log( 'Button '+buttonApi.text()+' was activated' );
} );;
} );

So using datatables I was able to get the selected row count. From that I parse the object through a loop for the first row entries.
Finally I call on the reduced array for the position value that I want (in this case position 1 is my Record ID field, more if you want) and push it to a new array.
From that you submit to your traditional controller for processing.
Hope this helps those trying to pass selected Row Data
$(document).ready(function() {
$('.stay').DataTable( {
dom: "<'row'<'col-sm-8'B><'col-sm-4'f>>"+ 'rt' + "<'row'<'col-sm-6'i><'col-sm-6'p>>",
buttons: [
'selectNone',
'selectAll',
{
extend: 'selected',
text: 'Assign Rooms',
action: function ( e, dt, node, config ) {
var rows = dt.rows( { selected: true } ).count();
var selected_rows = dt.rows( {selected: true} ).data(0);
var selected_ids = [];
for (i=0; i < rows; i++) {
var reduced_object = selected_rows[i];
selected_ids.push(reduced_object[1]);
};
console.log(selected_ids);
url = window.location;
// index = url.indexOf("housekeeper")
// alert(index);
// alert( 'There are '+rows+'(s) selected in the table' );
// alert(selected_rows[0])
// $.ajax({
// url: "/BookCreate/?mdate="+mdate+"&phone="+phone,
// type: "post",
// data: values,
// success: function(){
// alert('Saved Successfully');
// },
// error:function(){
// alert('Error');
// }
// });
}
},
{
extend: 'colvis',
text: 'Columns',
autoClose: true,
},
{
extend: 'copy',
text: '<i class="fa fa-files-o"></i>',
exportOptions: {
columns: ':visible'
}
},
{
extend: 'excel',
text: '<i class="fa fa-file-excel-o"></i>',
exportOptions: {
columns: ':visible'
}
},
{
extend: 'csv',
text: '<i class="fa fa-file-code-o"></i>',
exportOptions: {
columns: ':visible'
}
},
{
extend: 'pdf',
text: '<i class="fa fa-file-pdf-o"></i>',
exportOptions: {
columns: ':visible'
}
},
{
extend: 'print',
text: '<i class="fa fa-print"></i>',
exportOptions: {
columns: ':visible'
}
},
],
columnDefs: [ {
visible: false
} ],
columnDefs: [ {
orderable: false,
className: 'select-checkbox',
targets: 0
} ],
select: {
style: 'os',
selector: 'td:first-child',
style: 'multi'
},
order: [[ 2, 'asc' ]]
} ).on( 'buttons-action', function ( e, buttonApi, dataTable, node, config ) {
// action put here
console.log( 'Button '+buttonApi.text()+' was activated' );
} );;
} );

Related

I want to show the data received in my socket event into ajax datatable

I am using socket to receive the json data from my backend. I am receiving the data in the DATA variable and want to iterate it into the ajax datatable. Here is my code.
`
socket.on('getinvoices', (data) => {
var table = $('#table1').DataTable( {
dom: 'Bfrtip',
buttons: [
'copy', 'csv', 'excel', 'pdf', 'print'
],
order: false,
ajax: {
url : "https://testdma.tech-east.com.pk/dma/invoices/getAllInvoices",
dataSrc: "doc",
order: [[0]],
},
columns: [
{ data: 'recipientName' },
{ data: 'recipientAddress' },
{ data: 'recipientPhoneNumber' },
{ data: 'recipientEmail' },
{ data: 'services[/ ].serviceName' },
{ data: 'services[/ ].servicePrice' },
{
data: null,
className: "dt-center editor-delete",
orderable: true,
"mRender" : function ( data, type, row ) {
return '<button class="btn viewbtn" value=' +data._id +'>Edit</button>';
}
},
{
data: null,
className: "dt-center editor-delete",
orderable: true,
"mRender" : function ( data, type, row ) {
return '<button class="btn viewbtn2" value=' +data._id +'>Print Invoice</button>';
}
}
],
});
The data variable on in the socket is where I am receiving my data into.
I tried putting the DATA instead of URL into the ajax datatable but it didnt worked.Kindly guide me how can i populate table with that data
I'm pretty sure to populate a jQuery DataTable with data from a socket event, you can use the ajax.reload() method to update the table's data. Here is an example of how you could do this:
// Define the table
var table = $('#table1').DataTable({
dom: 'Bfrtip',
buttons: [
'copy', 'csv', 'excel', 'pdf', 'print'
],
order: false,
columns: [
{ data: 'recipientName' },
{ data: 'recipientAddress' },
{ data: 'recipientPhoneNumber' },
{ data: 'recipientEmail' },
{ data: 'services[/ ].serviceName' },
{ data: 'services[/ ].servicePrice' },
{
data: null,
className: "dt-center editor-delete",
orderable: true,
"mRender" : function ( data, type, row ) {
return '<button class="btn viewbtn" value=' +data._id +'>Edit</button>';
}
},
{
data: null,
className: "dt-center editor-delete",
orderable: true,
"mRender" : function ( data, type, row ) {
return '<button class="btn viewbtn2" value=' +data._id +'>Print Invoice</button>';
}
}
]
});
// Handle the 'getinvoices' socket event
socket.on('getinvoices', (data) => {
// Update the table data with the data from the socket event
table.ajax.reload(null, false);
});
You can also specify the data source and other options for the table by passing an object to the ajax.reload() method.
table.ajax.reload({
url: "https://testdma.tech-east.com.pk/dma/invoices/getAllInvoices",
dataSrc: "doc",
order: [[0]],
});

Warning - DataTables warning: table id=example - Cannot reinitialise DataTable

I am trying to get data from .JSON file and filter it in realtime.
But I am getting Warnings as
DataTables warning: table id=example - Cannot reinitialise DataTable. For more information about this error, please see http://datatables.net/tn/3
As per instructions in above link I added retrieve: true, and paging: false, But still warnings are shown.
I am new for jscript and jquery so can you please help me to resolve this warning
main.js file
$(document).ready(function () {
var table = $('#example').DataTable({
retrieve: true,
paging: false,
ajax: {
url: './test.json',
dataSrc: '',
},
columns: [
{ data: 'Host' },
{ data: 'Category' },
{ data: 'Type' },
{ data: 'SSH' },
{ data: 'Status' },
{ data: 'Notes' },
],
mark: true,
dom: 'Bfrtip',
lengthMenu: [
[10, 25, 50, 100, -1],
['10 rows', '25 rows', '50 rows', '100 rows', 'Show All']
],
buttons: [
'pageLength',
{
extend: 'copyHtml5',
exportOptions: {
columns: ':visible'
}
},
{
extend: 'excelHtml5',
exportOptions: {
columns: ':visible'
}
},
{
extend: 'csvHtml5',
exportOptions: {
columns: ':visible'
}
},
{
extend: 'print',
exportOptions: {
columns: ':visible'
}
},
{
extend: 'pdfHtml5',
download: 'open',
exportOptions: {
columns: ':visible'
}
},
'colvis'
],
columDefs: [{
targets: -1,
visible: false
}],
});
$('#example tfoot th').each(function () {
var title = $('#example tfoot th').eq($(this).index()).text();
$(this).html('<input type="text" placeholder="Search ' + title + '" />');
});
table.columns().eq(0).each(function (colIdx) {
$('input', table.column(colIdx).footer()).on('keyup change', function () {
table
.column(colIdx)
.search(this.value)
.draw();
});
});
});

page number not working in datatable export to pdf

I am trying to add page number in datatble pdf export, I got code from its official site after adding this code pdf button got disappearing and getting 'Uncaught ReferenceError: doc is not defined
at HTMLDocument' error in console.
$('#table2').DataTable({
dom: 'Bfrtip',
buttons: [
{
extend: 'pdfHtml5',
title: 'Data export',
filename: 'dt_custom_pdf',
pageSize: 'A4',
exportOptions: {
columns: ':visible',
search: 'applied',
order: 'applied'
},
},
doc['footer']=(function(page, pages) {
return {
columns: [
'Left part of footer',
{
alignment: 'right',
text: [
{ text: page.toString(), italics: true },
' of ',
{ text: pages.toString(), italics: true }
]
}
],
margin: [10, 0]
}
});
]
});
You did not define customize function to dataTable that why getting doc error you need to change
$('#table2').DataTable({
dom: 'Bfrtip',
buttons: [
{
extend: 'pdfHtml5',
text: 'Pdf',
filename: 'dt_custom_pdf',
pageSize: 'A4',
exportOptions: {
columns: ':visible',
search: 'applied',
order: 'applied'
},
customize: function ( doc ) {
doc['footer']=(function(page, pages) {
return {
columns: [
{
alignment: 'center',
text: [
{ text: page.toString(), italics: true },
' of ',
{ text: pages.toString(), italics: true }
]
}
],
margin: [10, 0]
}
});
}
}
]
});

Datatable does not print all my rows on scrolling

I am trying to get rows from back-end response on each scroll. I get
an AJAX response, but I can't get full row, it eats up the data
most probably the last one.
I tried with so other alternative, but it's not working at all, I tried redraw and reload in AJAX.
Here goes my js code:
var table= $('#subscriber_list').DataTable({
responsive: true,
"processing":true,
serverSide: true,
"scrollCollapse":true,
"sDom":"BifrtS",
scrollY:'35vh',
scrollCollapse: true,
paging:false,
"oScroller": {
"displayBuffer": 2,"loadingIndicator": true
},
"ajax": {"url": $('#data_table_column_list').attr("url"),"type": 'POST',"data":{'type':subscriber_type,'end_date_from':end_date_from,'end_date_to':end_date_to}},
"columns": JSON.parse($('#data_table_column_list').val().replace(/\'/g, '"')),
"columnDefs": [
{ "orderable": false, "targets": 2 }
],
buttons: [
{
extend: 'excelHtml5',
text: 'Export selected',
exportOptions: {
columns: ':visible:not(.not-exported)',
modifier: {
selected: true
}
},
title: 'Data export'
},
{
extend: 'excelHtml5',
text: 'Export All',
exportOptions: {
columns: ':visible:not(.not-exported)'
},
title: 'Data export'
}
]
});
You need one or both of the following depending on how you want the table to work.
Right now, it's getting cut off because the default in Datatables is 10 rows. You have paging set to false, so any results after the 10th are now shown.
Either switch this: paging:false,
to: paging:true,
That'll give you multiple pages of results with 10 on each page.
You can also add "pageLength": 50 or some other value if you want more than 10 rows per page.
here i am using same data table from multiple radio button switch, on switching i get warning from data table can't be re-initialised , since i know when i use table.destroy(); it destroy's all the object's created at while i switch the options, but have alternate to use it , what to do now ???? , running out of idea
i was referring this actually
https://datatables.net/manual/tech-notes/3
$('.subscriber_type').on('change',function (e){
var table = $('#subscriber_list').DataTable();
subscriber_data_table($(this).val(),$('#datepicker_from').val(),$('#datepicker_to').val());
});
subscriber_data_table("all",null,null);
function subscriber_data_table(subscriber_type,end_date_from,end_date_to) {
$('#subscriber_list').DataTable({
responsive: true,
"processing": true,
serverSide: true,
paging:true,
"pageLength":50,
"drawCallback": function( settings ) {
console.log( 'hit began' );
},
"sScrollY": "379",
"sDom":"BifrtS",
"oScroller": {
"displayBuffer": 2,"loadingIndicator": true
},
"ajax": {"url": $('#data_table_column_list').attr("url"),"type": 'POST',"data":{'type':subscriber_type,'end_date_from':end_date_from,'end_date_to':end_date_to}},
"columns": JSON.parse($('#data_table_column_list').val().replace(/\'/g, '"')),
"columnDefs": [
{ "orderable": false, "targets": 2 }
],
buttons: [
{
extend: 'excelHtml5',
text: 'Export selected',
exportOptions: {
columns: ':visible:not(.not-exported)',
modifier: {
selected: true
}
},
title: 'Data export'
},
{
extend: 'excelHtml5',
text: 'Export All',
exportOptions: {
columns: ':visible:not(.not-exported)'
},
title: 'Data export'
}
]
});
}

Bootstrap DataTable exclude certain visible columns from export

I can export dynamically selected visible columns to pdf with the following. However I want to be able to also exclude certain visible columns (button columns) too. How do I do this?
buttons: [{
extend: 'csv',
orientation: 'landscape',
pageSize: 'LEGAL',
text: 'Export as CSV',
exportOptions: {
columns: ':visible'
}
}, {
extend: 'pdfHtml5',
orientation: 'landscape',
pageSize: 'LEGAL',
text: 'Export as PDF',
exportOptions: {
columns: ':visible'
}, {
extend: 'colvis',
text: 'Show/Hide Columns'
}]
The key was to add a method to the columns property in the export options that filters if the column is visible and if the column is not part of the columns you do not want to export. The idx variable is the column index.
Working example here: https://jsfiddle.net/L06yu0vz/1/
$(document).ready(function() {
// Do not export these columns
var hideFromExport = [0,1,2];
var table = $('#example').DataTable({
dom: 'Bfrtip',
buttons: [{
extend: 'copyHtml5',
exportOptions: {
columns: function ( idx, data, node ) {
var isVisible = table.column( idx ).visible();
var isNotForExport = $.inArray( idx, hideFromExport ) !== -1;
return isVisible && !isNotForExport ? true : false;
}
}
}, 'colvis']
});
});

Categories