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/
Related
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 have a DataTable that requires me to retrieve the longest .text() element of each column. To achieve this, I've implemented the following script.
$('#example').DataTable({
deferRender: true,
autoWidth: false,
drawCallback: function () {
var table = $('#example').DataTable();
table.columns().every(function () {
var longestSoFar = -1;
var longestItem;
this.nodes().to$().each(function () {
var text = $(this).text();
if (text.length > longestSoFar) {
longestSoFar = text.length;
longestItem = this;
}
});
var longestTD = $(longestItem).html();
console.log(longestTD);
});
}
});
This scripts works proper and logs the longest .text() element of each column, but if you filter, it continues to pull from the entire list of rows per column regardless if their visible or not.
Example... "unfiltered"
FISH
Trout (visible)
Catfish (visible)
Coelacanth (visible)
In this scenario, my function returns "Coelacanth", which is proper.
Example... "filtered"
If I filter this DataTable for "Cat"... only one visible row would be displayed... "Catfish".
FISH
Trout (hidden)
Catfish (visible)
Coelacanth (hidden)
In this scenario, my function should return "Catfish", but instead it continues to return "Coelacanth". Is there a way to have this ignore any filtered rows and only pull from the "filtered" items visible on screen?
Thanks in advance.
SOLUTION
Use appropriate selector-modifier ({ search: 'applied' }) to account for current search query, if applicable:
// ... skipped ...
table.columns().every(function (index) {
var longestSoFar = -1;
var longestItem;
var column = table.column(index, { search: 'applied' });
column.nodes().to$().each(function () {
// ... skipped ...
DEMO
See this jsFiddle for code and demonstration.
NOTES
There was a issue with jQuery DataTables versions 1.10.6 - 1.10.9 where selector-modifier ({ search: 'applied' }) couldn't be used as a parameter to columns().every() API method, see this issue #679.
If using nightly build or jQuery DataTables version released after 1.10.9, it is possible to use the code below:
// ... skipped ...
var table = $('#example').DataTable();
table.columns({ search: 'applied' }).every(function (index) {
this.nodes().to$().each(function () {
// ... skipped ...
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.
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'm using jQuery DataTables to format a table, and I want to create a button that filters rows on all pages. Currently the filter (which toggles visibility of rows containing text with the color #bfbfff) only applies to the currently visible page.
I know that I'd have to use the DataTables API to make this work, I just don't know how to integrate my existing jQuery into the API.
$("a#notes").on("click", function() {
$("#example tbody tr").toggle();
$("#example tbody tr td span[style='color:#bfbfff;']").closest("tr").toggle();
} );
Fiddle showing filter only applying to current page
With the latest DataTables API:
var _fieldNotesFilter = false;
$.fn.dataTable.ext.search.push( function ( settings, searchData, index, rowData, counter ) {
if ( settings.nTable.id !== 'example' ) {
return true;
}
if ( ! _fieldNotesFilter ) {
return true;
}
else if ( rowData.item.match(/rgb\(191, 191, 255/) || rowData.item.match(/#bfbfff/) ) {
return true;
}
return false;
} );
$(document).ready( function () {
$('#filter_notes').on( 'click', function () {
//Invert the filtering flag
_fieldNotesFilter = ! _fieldNotesFilter;
// Redraw the table to update the filtering change
$('#example').DataTable().draw();
} );
} );
You could include your own filter in order to make it work to the whole data (all pages). Read more about filtering in datatables here.
The working fiddle using your example.
The javascript must be something like:
$(document).ready(function() {
var oTable = $('#example').dataTable();
$("a#notes").on("click", function() {
oTable.dataTableExt.afnFiltering.push(
function( oSettings, aData, iDataIndex ) {
var tr = oTable.fnGetNodes(iDataIndex);
var result=$(tr).find("td span[style='color:#bfbfff;']");
return result.length;
});
oTable.fnDraw();
});
});