I'm using jQuery Datatables pluging to view some data and I have in my table two columns containing checkboxes, I've tried to export the data from the table to an XSLX file using excel and excelHtml5 and also excelFlash buttons but I get two empty columns in the file, I've also included JSZip plugin in my project but in vain. How can I get the values of these checkboxes as booleans in my file.
SOLUTION
You're using DataTables 1.10.8. Before this version (1.10.7 and earlier) there was TableTools with fnCellRender option that would help to do what you want. Since 1.10.8 TableTools extension has been replaced with Buttons extension.
With Buttons extension you may use exportOptions and tell DataTables that you want the the data used for sorting (orthogonal: 'sort'). Then you need to define render function and return appropriate data when sorting is performed (type === 'sort').
/*
* Create an array with the values of all the checkboxes in a column
*/
$.fn.dataTable.ext.order['dom-checkbox'] = function (settings, col) {
return this.api()
.column(col, { order: 'index' })
.nodes()
.map(function (td, i) {
return $('input', td).prop('checked') ? '1' : '0';
});
};
var table = $('#example1').DataTable({
dom : 'Bfrtlip',
buttons: [
{
extend: 'excel',
exportOptions: {
orthogonal: 'sort'
}
}
],
columnDefs: [{
targets:[0,5],
orderDataType: 'dom-checkbox',
render: function(data, type, row, meta){
if(type === 'sort'){
var api = new $.fn.dataTable.Api( meta.settings );
var $input = $(api.cell({ row: meta.row, column: meta.col }).node()).find('input');
data = $input.prop('checked') ? '1' : '0';
}
return data;
}
}]
});
table.buttons().container()
.appendTo( $('.col-sm-6:eq(0)', table.table().container() ) );
DEMO
See this jsFiddle for code and demonstration.
Related
Row Content Sample: (this content is loaded from a json array txt file)
<div class='debug'><a href='/DH033368-4041-SR-0910-00005-006-0-CPC-20131105-1652/debug/DH033368-4041-SR-0910-000-Stage 1B Client Review-filteredCommentsXFDF.xml' target='_blank'>[webdav]</a> : /Company Home/filteredCommentsXFDF.xml</div>
I need to either find the debug class within a DataTable row(s) or search for '/debug/' in the "href" attribute and if found hide the row.
Javascript is not my strong suite. Any help is appreciated.
What I have so far:
$("#hide").click(function() {
console.log('HIDE');
$.fn.dataTable.ext.search.push(
function(settings, data, dataIndex) {
return $(table.row(dataIndex).node()).data().search("/debug/");
}
);
table.draw();
});
$("#reset").click(function() {
console.log('RESET');
$.fn.dataTable.ext.search.pop();
table.draw();
});
Thanks
Use to$() to convert the row node to a jQuery instance. This is more easy to work with. Then simply test the <div> and the <a> href for the desired matches :
$('#hide').click(function() {
$.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {
var $row = table.row(dataIndex).nodes().to$();
return $row.find('div').hasClass('debug') ||
$row.find('a').attr('href').indexOf('/debug/')>-1
})
table.draw()
})
demo -> http://jsfiddle.net/3co6Lvkx/
I am using jQuery and datatables. I want to add a class to the TR element of a particular row. I know how to find the row. The console.dir(row); shows the row object and that starts with a tr element. I can't get the jQuery selector to do anything though. What am I missing?
table = $('#resultTable').DataTable({
aaSorting: [],
ajax: {...},
columnDefs: [...],
createdRow: function (row, data, index) {
//
// if the second column cell is blank apply special formatting
//
if (data[1] == "") {
console.dir(row);
$('tr', row).addClass('label-warning');
}
}
});
$('tr', row) is looking for a tr element in the context of row, meaning it will search for a tr element inside the row provided as context parameter.
According to API, this should work
$(row).addClass("label-warning");
You would just have to use the createdRow
$('#data-table').DataTable( {
createdRow: function( row, data, dataIndex ) {
// Set the data-status attribute, and add a class
$( row ).find('td:eq(0)')
.attr('data-status', data.status ? 'locked' : 'unlocked')
.addClass('asset-context box');
}
} );
DataTable().row.add() situation:
If you want to add class when using row add function in Datatables, you could get the TR-DOM from node() method:
var datatable = $('#resultTable').DataTable();
var trDOM = datatable.row.add( [
"Col-1",
"Col-2"
] ).draw().node();
$( trDOM ).addClass('myClass');
To set the Id attribute on the row <tr> use:
//....
rowId: "ShipmentId",
columns: [...],
//....
To set a class name on the <tr> use this calback
createdRow: function (row, data, dataIndex) {
$(row).addClass('some-class-name');
},
ref: https://datatables.net/reference/option/createdRow
To set a class on the <td> use
"columns": [
{
data:"",
className: "my_class",
render: function (data, type, row) { return "..."; }
},
{
data:"",
className: "my_class",
render: function (data, type, row) { return "..."; }
},
//...
]
Something similar for 'columnDefs'
ref: https://datatables.net/reference/option/columns.className
Also you can add class to tr by pass through json data that you send to datatable. It's enough that every json item has DT_RowClass.
For example:
{
DT_RowAttr = new
{
attr1 = "1",
attr2 = "2"
}
DT_RowClass = "majid",
DT_RowId = "rowId"
}
In this example DT_RowId value apply to id attribute of any tr tag and DT_RowAttr value apply some custom attribute to tr tag.
Another solution:
createdRow: function (row,data) {
var stsId = data.Ise_Sts_Cost_ID;
if (stsId == 3)
$(row).addClass('table-warning');
else if (stsId == 4)
$(row).addClass('table-success');
else
$(row).addClass('table-danger');
}
I was wondering if the rendering of the table after receiving an ajax response can be modified. This seems related to the render function described here: https://www.datatables.net/manual/orthogonal-data.
My server returns Data like
{
"name":
{
id: "123456",
value: "Tiger Nixon"
}
}
I want to add to each name cell the id of the name as data-attribute or as id for the td and want to add a .on( "click", handler ) for each cell.
Is this possible?
Thanks in advance
You can use DT_RowData or DT_RowAttr (requires DataTables 1.10.5 or higher) parameters in your returned data to assign attributes to <tr> element which you can later retrieve in click handler, see Server-side processing chapter in the manual.
Alternatively you can use render method but it may not be as effective. I assumed below that index of your name column is 0 and that you want to set data-id attribute.
var table = $('#example').DataTable({
"columnDefs": [{
"data": "name.value",
"targets": 0,
"render": function ( data, type, full, meta ) {
if(type === 'display'){
$('#example').DataTable().cell(meta.row, meta.col).nodes().to$().attr('data-id', full['name']['id']);
}
return data;
}
}]
});
You can add click event handler using the code below:
$(document).ready(function(){
var table = $('#example').DataTable({
// Define DataTables initialization options here
});
$('#example tbody').on('click', 'td', function(){
// Use table to access various API function
//
// For example:
// var data_cell = table.cell(this).data();
});
});
This is possible by using the columns.createdCell function.
The answer of Gyrocode is correct for an old DataTables version.
I am trying to copy the selected rows in the table, when I click the buttons for copy,csv, excel, print the entire table copying and downloading.
How to get the selected rows in the table, and copied to clipboard, save as the file.
Javascript:
$(document).ready(function() {
var table = $('#example').DataTable( {
"dom": 'T<"clear"><"H"lfr>t<"F"ip>',
"tableTools": {
"sSwfPath": "/swf/copy_csv_xls_pdf.swf"
},
initComplete: function () {
var api = this.api();
api.columns().indexes().flatten().each( function ( i ) {
var column = api.column( i );
var select = $('<select><option value=""></option></select>')
.appendTo( $(column.footer()).empty() )
.on( 'change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search( val ? '^'+val+'$' : '', true, false )
.draw();
} );
column.data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' )
} );
} );
}
} );
$('#submitFrm').click( function() {
var data = table.$('input, select').serialize();
alert(
"The following data would have been submitted to the server: \n\n"+
data.substr( 0, 120 )+'...'
);
return false;
} );
} );
With copy, save, print, buttons and also the individual filter on the column.But the thing is selected rows are not copying in the clipboard and csv after downloading showing entire data not selected rows.
How to copy,csv .. only the selected rows in the table.
Thanks
http://jsfiddle.net/dbecbww1/
just an example. for additional questions, you might need to
post again another question.
check if it is also working for your buttons, if not,
configure your datatableTools.tableTools.js
function "_fnGetDataTablesData", try to debug.
I've tried manipulating it before.
FYI:
you can set which columns you only need to copy for your files.
NOTE: set your swf path normally, which I think you have done already. the swf path for the fiddle is not working so the buttons won't work. I've been searching for working swf paths online but to no avail. Mine works perfectly fine in my local project, though.
I am using jQuery Tabelsorter and it's working great.
But I want inside every -field an input-tag where the value for the sorting-script is located inside the input value param.
NOW: <td><?php echo $value; ?></td>
GOAL: <td><input value="<?php echo $value; ?>"></td>
How can I tell jQuery Tablesorter the new "value" location?
Found at Tablesorter 2.0 Samples http://tablesorter.com/docs/example-option-text-extraction.html
Example:
textExtraction: function(node) {
// extract data from markup and return it
return node.childNodes[0].childNodes[0].innerHTML;
}
My try but not working:
textExtraction: function(node) {
// extract data from markup and return it
return node.childNodes[0].val();
}
Instead of table sorter use kendoui.its provide more features & easy to use
kendoui
Tthe original tablesorter plugin has an issue using the updateCell method, so this method will not work when updating input values. But you can try my fork of tablesorter which doesn't have this issue.
Here is a demo of the all of the code below put together.
Basically instead of using textExtraction which applies to ALL table cells, you just need to add a parser:
$.tablesorter.addParser({
id: "inputs",
is: function () {
return false;
},
format: function (s, table, cell) {
return $(cell).find('input').val() || s;
},
type: "text"
});
then tell tablesorter which column to apply it to (zero-based index):
$('table').tablesorter({
headers: {
0: { sorter: "inputs" } // zero-based index (first column = column 0)
}
});
Then make sure any changes to the inputs (unless you make them read-only) are recognized by tablesorter and sent to your server
var resort = true, // resort table after update
// update all input types within the tablesorter cache when the change event fires.
// This method only works with jQuery 1.7+
// you can change it to use delegate (v1.4.3+) or live (v1.3+) as desired
// if this code interferes somehow, target the specific table $('#mytable'),
// instead of $('table')
$(window).load(function () {
// this flag prevents the updateCell event from being spammed
// it happens when you modify input text and hit enter
var alreadyUpdating = false;
$('table').find('tbody').on('change', 'input', function (e) {
if (!alreadyUpdating) {
var $tar = $(e.target),
$table = $tar.closest('table');
alreadyUpdating = true;
$table.trigger('updateCell', [ $tar.closest('td'), resort ]);
// *** update your server here ***
setTimeout(function () {
alreadyUpdating = false;
}, 10);
}
});
});