How to add a class to the <td> in server-side processing mode - javascript

When using server-side processing on a DataTable, there is a mechanism to add an ID, class, or data-* attribute to the table row (<tr>) by including the DT_RowId, DT_RowClass or DT_RowData properties, respectively, to the JSON data for each row: https://datatables.net/examples/server_side/ids.html.
Is there a similar (or any) mechanism for adding additional markup to the table columns (<td>)?

You can add classes to columns like so, but not sure if this gets you where you want to go:
var all_data = data;
$("#example").DataTable({
"data": all_data,
"aoColumns": [{
"data": 'cat_code',
"className": "lang_body_2",//you can add whatever you want for a specific column here.
"visible": false
}, {
"data": 'value',
"searchable": false,
"width": "20%",
"className": "lang_body_2",
"title": ""
}]
})

Other way, from off. sites docs.
Assign class my_class to first column
$('#example').dataTable( {
"columnDefs": [
{ className: "my_class", "targets": [ 0 ] }
]
} );

Related

Datatables with Ajax

I'm new to dataTabels and I'm trying to get data from a json txt file (test1.txt). This is a part of it (only 4) but I have +5000:
[{"0":"22352442","ID":"22352442","1":"22126303","PARENT":"22126303","2":"2813340","TASK_ID":"2813340","3":"2667252","CHILD_ID":"2667252","9":"Shawne Walthall","LEAD":"Shawne Walthall","11":"RP ~217' cable- PL 8 YPSIL","DESCRIPTION":"RP ~217' cable- PL 8 YPSIL","12":"PD-SW-ANN","WORKLOCATION":"PD-SW-ANN","13":"IC","TASKTYPE":"IC","14":"HOLD","STATUS":"HOLD","15":"INFLD","C_STATUS":"INFLD","16":"Scheduled","CLASSIFICATION":"Scheduled","18":"RFW672917A11 INSTALL CABLE - 05-181","TASK_DESCRIPTION":"RFW672917A11 INSTALL CABLE - 05-181","19":"Overload","TYPE_OF_WORK":"Overload","20":"16-NOV-06","TS":"16-NOV-06","21":"24-JAN-11","TC":"24-JAN-11"},{"0":"27364695","ID":"27364695","1":"27364637","PARENT":"27364637","2":"11949147","TASK_ID":"11949147","3":"11949089","CHILD_ID":"11949089","11":"08-036 Design System Cable NF 52R Howard","DESCRIPTION":"08-036 Design System Cable NF 52R Howard","12":"PD-SE-TBY","WORKLOCATION":"PD-SE-TBY","13":"TC","TASKTYPE":"TC","14":"WAPPR","STATUS":"WAPPR","15":"INFLD","C_STATUS":"INFLD","16":"Scheduled","CLASSIFICATION":"Scheduled","18":"TEST CABLE","TASK_DESCRIPTION":"TEST CABLE"},{"0":"28728012","ID":"28728012","1":"28728001","PARENT":"28728001","2":"31575951","TASK_ID":"31575951","3":"31575940","CHILD_ID":"31575940","9":"Clifton Manus","LEAD":"Clifton Manus","11":"08-098, Design\/Construct System Cable","DESCRIPTION":"08-098, Design\/Construct System Cable","12":"PD-SE-TBY","WORKLOCATION":"PD-SE-TBY","13":"IC","TASKTYPE":"IC","14":"APPR","STATUS":"APPR","15":"INFLD","C_STATUS":"INFLD","16":"Scheduled","CLASSIFICATION":"Scheduled","18":"08-097, INSTALL CABLE","TASK_DESCRIPTION":"08-097, INSTALL CABLE","19":"Reliability","TYPE_OF_WORK":"Reliability","20":"12-AUG-08","TS":"12-AUG-08","21":"12-AUG-17","TC":"12-AUG-17"},{"0":"28728014","ID":"28728014","1":"28728001","PARENT":"28728001","2":"31575953","TASK_ID":"31575953","3":"31575940","CHILD_ID":"31575940","11":"08-098, Design\/Construct System Cable","DESCRIPTION":"08-098, Design\/Construct System Cable","12":"PD-SE-TBY","WORKLOCATION":"PD-SE-TBY","13":"TC","TASKTYPE":"TC","14":"WAPPR","STATUS":"WAPPR","15":"INFLD","C_STATUS":"INFLD","16":"Scheduled","CLASSIFICATION":"Scheduled","18":"TEST CABLE","TASK_DESCRIPTION":"TEST CABLE","19":"Reliability","TYPE_OF_WORK":"Reliability","20":"12-AUG-08","TS":"12-AUG-08","21":"12-AUG-08","TC":"12-AUG-08"}]
There is around 21 columns. How can I assign this to the columns in my dataTable?
This is my dataTable script:
var dataTables = $('#myTable').DataTable({
ajax: "test1.txt",
deferRender: true,
bPaginate: true,
select: {
style: 'multi'
},
aLengthMenu: [[100, 200, 500, -1], [100, 200, 500, "All"]],
pageLength: 100});
Make these changes in your datatable initialization.
ajax: {
url: "test1.txt",
dataSrc: ''
},
Remove columns: [ ]
You will then need to format your json text file such as this
[
{
"0" : "value of 1st column of 1st record",
"1" : "value of 2nd column of 1st record",
...
...
upto 21 column
},
{
"0" : "value of 1st column of 2nd record",
"1" : "value of 2nd column of 2nd record",
...
...
upto 21 column
}
]
Try this and see if it works.
If you want to hide column, then add this in datatable
"columnDefs": [
{
"targets": [ 0, 1 ],
"visible": false,
"searchable": false
}
]
Where 0, 1 represents you column index.
0 first column, 1 second column
Enter these index number of column which you want to hide.
New Update
In the dynamic json file case, you will need to use first approach using columns
Mention what columns you want to show in the columns key like below
$('#myTable').DataTable( {
"ajax": {
url: "test1.txt",
dataSrc: ''
},
"columns": [
{ "data": "C1" },
{ "data": "C2" }
]
});
and then your json text file will be like
[{"C1":"22352442","C2":"22126303","KEY":"NO SHOW"}, {"C1":"22352442","C2":"22126303", "KEY":"NO SHOW"}]
Your first json will work in the case now.

targets in columnDefs of Datatable

The documentation tells us the way we can use 'targets'
in columnDefs. But is there any way we can use it dynamically? For example, I have a global array (containing column numbers) which I update every time certain function is carried out on datatable. I want to render those columns in the global array in a particular fashion. I need to know if there is any way in which I could do this.
"columnDefs":[
{
"targets": hide_them,//name of the global array
"render": //some function
}
]
As per documentation Target of columnDefs in Datatable must use for below approach
0 or a positive integer column index counting from the left
$('#example').dataTable( {
"columnDefs": [ {
"targets": 0,
"searchable": false
} ]
} );
A negative integer such as column index counting from the right
$('#example').dataTable( {
"columnDefs": [ {
"targets": -0,
"searchable": false
} ]
} );
_all - A string - class name will be matched for all column as default work
$('#example').dataTable( {
"columnDefs": [ {
"targets": '_all',
"searchable": false
} ]
} );

Complex column widths with Jquery Datatables

I have created a datatable with the following code
$(document).ready( function () {
$('#data-table').DataTable( {
"bFilter": false,
"scrollY": 300,
"scrollX": true,
"paging": false,
"ordering": false,
"info": false,
"columnDefs": [
{ "width": "20%", "targets": 0 }
]
});
} );
Note that I have the widths set to 20% for each of the columns. My question is how do I specify a width for column 1 while still being able to set a width for the rest of the columns?
I've seen examples like this on the datatable website:
$('#example').dataTable( {
"columns": [
{ "width": "20%" },
null,
null,
null,
null
]
} );
But I do not think this will work for me because it looks as if it would require me to know how many columns my table has in advance, and user requirements require the number of columns to be variable.
Try replacing your columnDefs part with this (and adding the appropriate percentages):
"columnDefs": [
{ "width": "(percentage)%", "targets": "_all" }
{ "width": "(other percentage)%", "targets": 0 }
]
This will set the first column to one width and the others to a different width.
Targets define which column will be affected. Setting it as an integer will affect the columns starting from left to right (i.e. '"targets": [0, 1]' would affect the leftmost and second-leftmost columns). Negative integers affect the columns from right to left. The string "_all" will affect all columns.

Sorting on a column in removing html contents in Datatables 1.10

I am unsing datatable 1.10, In my code in one of the column as per the requirement I am adding an HTML checkbox tag.
Now first time when the table gets rendered it shows me those checkboxes but when I click on that column to sort or any other column for sorting then the column which contains HTML contains are getting wiped out. (I crosschecked this with the chrome DOM inspector... the td element contains nothing :()
Below is my dataTable initialization code.
dataTableOptions: function() {
return {
"orderable": true,
"columnDefs": undefined,
"autoWidth": true,
"deferRender": true,
"data": undefined
};
},
dtRowGroupingOptions: function () {
return {
bExpandableGrouping: true,
bExpandSingleGroup: false,
iExpandGroupOffset: -1,
asExpandedGroups: [""]
};
}
var dataTablesOptions = self.dataTableOptions();
dataTablesOptions.data = tableData;
dataTablesOptions["paginate"] = false;
dataTablesOptions["lengthChange"] = false;
dataTablesOptions["columnDefs"] = [{"targets": 0, "data": "serverName", 'title' : 'ServerName'},
{"targets": 1, "data": "COMMAND", 'title' : 'Command'},
{"targets": 2, "data": "PID", 'title' : 'Process Id'},
{"targets": 3, "data": "SIZE", 'title' : 'Size'},
{"targets": 4, "data": "USER", 'title' : 'User'},
{"targets": 5, "data": "action", 'title' : 'Actions', "type" : "html", "orderDataType": "dom-checkbox"}
];
dataTablesOptions["createdRow"] = function (nRow, aData, iDataIndex) {
var self = this;
if (aData["comments"] && aData["comments"].indexOf("Error") != -1) {
// Do not do anything
$('td:eq(0)', nRow).html(aData["serverName"]+"" +
"<a class='btn btn-danger' href='#' data-toggle='tooltip' title='Error in execution'><i class='icon-question'></i></a>");
}
return self;
};
var dcInfoDataTable = contentDiv.find('table.dcInfoTable').DataTable(dataTablesOptions);
I am also using datatables rowGrouping and searchhiglight plugin, below is the code.
// call row grouping
contentDiv.find('table.dcInfoTable').dataTable().rowGrouping(self.dtRowGroupingOptions());
// enable search highlighing
contentDiv.find('table.dcInfoTable').dataTable().fnSearchHighlighting();
Note: I tried removing rowGrouping plugin code just to make sure that this is not happeing because of this plugin but even after removing there is no effect, the HTML contents are getting wiped out.
Not only when you sort will it clear out your data, it will also clear it if you use any other feature that changes your table. This happens because each time the datatable draws for new data, it's clearing out your static data.
You need to re-append the checkboxes on each draw, you can do this in the fnDrawCallback event:
$(document).ready( function() {
$('#example').dataTable( {
"fnDrawCallback": function( oSettings ) {
alert( 'DataTables has redrawn the table' );
//append the checkbox to your table columns here...
}
} );
} );

jquery datatables: adding extra column

Scenario
I am using datatables (#version 1.9.4) for the first time to display data to the user.
I succeed in retrieving the data via ajax and in binding them to the datatable.
Now I want to add extra columns to let the user process the records. For semplicity sake, the aim is to add a button with an onclick handler that retrieve the data of the 'clicked' record.
In my plan I would bind the json item corresponding to the 'clicked' record to the onclick handler.
Till now, if I add an additional TH for the action column to the DOM, an error occurs from datatables code:
Requested unknown parameter '5' from data source for row 0
Question
How to set custom columns? How to fill their content with HTML?
Here is my actual config.
HTML
<table id="tableCities">
<thead>
<tr>
<th>country</th>
<th>zip</th>
<th>city</th>
<th>district code</th>
<th>district description</th>
<th>actions</th>
</tr>
</thead>
<tbody></tbody>
</table>
Javascript
$('#tableCities').dataTable({
"bPaginate": true,
"bLengthChange": false,
"bFilter": true,
"bSort": true,
"bInfo": false,
"bAutoWidth": true
, "bJQueryUI": true
, "bProcessing": true
, "bServerSide": true
, "sAjaxSource": "../biz/GetCitiesByZip.asp?t=" + t
});
Sample Json result
{
"aaData":
[
[
"IT",
"10030",
"VILLAREGGIA",
"TO",
"Torino"
],
[
"IT",
"10030",
"VISCHE",
"TO",
"Torino"
]
],
"iTotalRecords": 2,
"iTotalDisplayRecords": 2,
"iDisplayStart": 0,
"iDisplayLength": 2
}
Edit
Daniel is right. The solution is to set up the custom column in the aoColumnDefs, specifying the mData and the mRender properties. In particular mRender lets to define custom html and javascript.
/* inside datatable initialization */
, "aoColumnDefs": [
{
"aTargets": [5],
"mData": null,
"mRender": function (data, type, full) {
return 'Process';
}
}
]
You can define your columns in a different way
like this
"aoColumns": [
null,
null,
null,
null,
null,
{ "mData": null }
]
or this
"aoColumnDefs":[
{
"aTargets":[5],
"mData": null
}
]
Here some docs Columns
Take a look at this DataTables AJAX source example - null data source for a column
Note that prior to DataTables 1.9.2 mData was called mDataProp. The name change reflects the flexibility of this property and is consistent with the naming of mRender. If 'mDataProp' is given, then it will still be used by DataTables, as it automatically maps the old name to the new if required.
Another solution/workaround could be adding that '5' parameter...
For example adding extra "" to each row
like this:
[
"IT",
"10030",
"VILLAREGGIA",
"TO",
"Torino",
""
],
[
"IT",
"10030",
"VISCHE",
"TO",
"Torino",
""
]
Just in case anyone using a newer version of DataTables (1.10+) is looking for an answer to this question, I followed the directions on this page:
https://datatables.net/examples/ajax/null_data_source.html
Posting this answer here, just to show that where the aoColumnDefs needs to be defined. I got help from this question it self, but I struggled for a while for where to put the aoColumnDefs. Further more also added the functionality for onclick event.
$(document).ready(function() {
var table = $('#userTable').DataTable( {
"sAjaxSource": "/MyApp/proctoring/user/getAll",
"sAjaxDataProp": "users",
"columns": [
{ "data": "username" },
{ "data": "name" },
{ "data": "surname" },
{ "data": "status" },
{ "data": "emailAddress" },
{ "data" : "userId" }
],
"aoColumnDefs": [
{
"aTargets": [5],
"mData": "userId",
"mRender": function (data, type, full) {
return '<button href="#"' + 'id="'+ data + '">Edit</button>';
}
}
]
} );
$('#userTable tbody').on( 'click', 'button', function () {
var data = table.row( $(this).parents('tr') ).data();
console.log(data);
$('#userEditModal').modal('show');
});
} );

Categories

Resources