Datatables sorting - how to ignore text in column? - javascript

I have used this script to sort my datatable and ignore text that I do not want to sort, I'll explain.
this is the column example:
10,836
↑(10.71%)
14,836
↑(13.71%)
I want to ignore this: ↑(10.71%) and to sort according to this: 10,836.
thats my script:
jQuery.extend(jQuery.fn.dataTableExt.oSort, {
"justNum-pre": a => parseFloat(a.replace(/\D/g, "")),
"justNum-asc": (a, b) => a - b,
"justNum-desc": (a, b) => b - a
});
$(document).ready(function () {
var table = $('#dataTable').DataTable({
order: [[ 1, "desc" ]],
scrollY: 200,
scrollX: false,
responsive: true,
paging: false,
//colReorder: true,
//pageLength: 100,
columns: [
{
"render": function(data, type, row){
return data.split(" ").join("<br/>");
}
},
null,
null,
null,
null,
null,
null
],
columnDefs: [
{ className: "all", "targets": [ 0, 1, 3, 6 ] },
{
type: 'justNum',
targets: 1
}
]
});
});

You can do this using the DataTables orderData feature.
For example, assume your formatted data is in the first column:
10,836
↑(10.71%)
Add a second column containing only the numeric portion (no text) 10836 and define it as a hidden column.
Then, create a columnDefs section in your datatable definition - something like this:
$('#demo').DataTable( {
"columnDefs": [
{ "orderData": [ 1 ], "targets": 0 },
{ "visible": false, "targets": 1 }
]
} );
} );
This says that the first column (target index 0) will use the data in the second column (target index 1) for sorting. And the second column will be a hidden column.

Related

Pushing value in array in second ajax get request

I'm using DataTables to fill a table and need some data from a different source. So I started off with render and made a second ajax request by the ID's of what I need the name of.
Here is my code, that will explain it more clearly.
$('#table').DataTable({
"ajax": "/api/url",
"language": {
"url": "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/German.json"
},
"order": [[0, "asc"]],
"pagingType": "simple",
"responsive": {details: false},
"bAutoWidth": true,
"lengthChange": true,
"scrollX": false,
"aoColumnDefs": [{}],
"columns": [
{
"data": "typ_name"
},
{
"data": "mietpreise",
render: function (data, type, row, meta) {
let tmp = [],
currentCell = $("#table").DataTable().cells({
"row": meta.row,
"column": meta.col
}).nodes(0);
data.forEach(function (item) {
$.get("/api/url2/" + item.preis_kundengruppe_id, function (row, status) {
tmp.push(row.data.kundengruppe_name);
});
});
console.log(tmp);
return $(currentCell).text(tmp);
}
},
I'm expecting to have the value of kundengruppe_name in the array like ['case1', 'case2'] but in the console I get this
[]
0: "Endkunden"
1: "Händler"
length: 2
__proto__: Array(0)
So what I want is to find under 0 and 1 and not in the array as expected. What am I doing wrong? What's going on with the array?

Uncaught TypeError: Cannot read property 'style' of undefined using datatable pipeline

I am using Datatable pipeline for generating table. My table has dynamic column means it has no fixed column. The column column number changes with the change of a month. Suppose, during current month the table has 4 column but for november it has 32 columns. When I changes month to november,it gives me Cannot read property 'style' of undefined this error.
My datatable initilization function:
function monthlyAttendanceStatusDatatableInit(tableIdOrCss, url, columns, sortArr, pageLength, year, month) {
console.log(columns);
var param = {
"responsive": false,
// "columnDefs": [
// {responsivePriority: 1, targets: -1},
// {responsivePriority: 2, targets: 0}
// ],
"aLengthMenu": [[10, 20, 50, -1], [10, 20, 50, 'All']],
"pageLength": pageLength || 10,
"iDisplayLength": pageLength || 10,
//"language": { search: "" },
"sPaginationType": "simple_numbers", // you can also give here 'simple','simple_numbers','full','full_numbers'
"oLanguage": {
"sSearch": "Search:",
"sProcessing": "Loading..."
},
"ajax": $.fn.dataTable.pipeline( {
url: url,
data: {
'month': month,
'year': year
},
pages: 2 // number of pages to cache
}),
"processing": true,
"serverSide": true,
"searching": true,
// "bPaginate": true,
// "fnDrawCallback":function(){
// if(typeof callBack == 'function'){
// callBack();
// }
// },
"destroy": true,
"paging": true,
"retrieve": false,
"aoColumns": columns,
"aaSorting": sortArr, //[[ 0, "asc" ],[ 1, "desc" ]] // Sort by first column descending
// "scrollX": true,
// "createdRow": function( row, data, dataIndex ) {
// $(row).attr('id', 'employee-'+data.id);
// }
};
// $(tableIdOrCss).remove();
var table = $(tableIdOrCss).DataTable(param);
return table;
}
I genrating column using server side data.
Columndefinition function:
function getColumnDefinition(year, month) {
var columns = [
{"sTitle": "ID", "mData": "e_id", "bSortable": true},
{"sTitle": "Employee Name", "mData": "employee_name", "bSortable": true},
];
var totalDay = getDayCount(year, month);
var monthS = month.slice(0, 3);
for (var i = 1; i <= totalDay; i++) {
if (i < 10) {
var date = '0' + i.toString();
}else {
var date = i.toString();
}
var dateColumn = {"sTitle": date + "-" + monthS, "mData": date, "bSortable": true};
columns.push(dateColumn);
}
return columns;
}
I am unable to find any solution
As you can see on DataTable documentation for destroy() method, in the case of column change, you should destroy datatable instance and remove all child nodes of the table element with jQuery#empty() call before adding new columns.
var table = $('#myTable').DataTable();
$('#submit').on( 'click', function () {
$.getJSON( 'newTable', null, function ( json ) {
table.destroy();
$('#myTable').empty(); // empty in case the columns change
table = $('#myTable').DataTable( {
columns: json.columns,
data: json.rows
} );
} );
} );
Here it is the working example.

Pass an Array as a parameter does not work

I am using DataTables.js and want to pass an array as a parameter:
This piece of code works (see columnDefs):
var table = $('#html_table').DataTable({
paging: false,
language: {
searchPlaceholder: "e.g.: .msg, AU2019-00XX",
search: "Filter Results"
},
order: [
[response.order_by_column, response.order_by]
],
columnDefs: [
{ width: 70, targets: 0 }, { width: 50, targets: 1 }, { width: 50, targets: 2 },
{otherStuff...},
{otherStuff...}
]
But this piece of code does not work (see columnDefs):
Array Creation
html_col_width = []
for(i=0; i<response.html_col_width.length; i++){
html_col_width.push({
"width": response.html_col_width[i],
"targets": i
})
}
Data Table Creation
var table = $('#html_table').DataTable({
paging: false,
language: {
searchPlaceholder: "e.g.: .msg, AU2019-00XX",
search: "Filter Results"
},
order: [
[response.order_by_column, response.order_by]
],
columnDefs: [
html_col_width,
{otherStuff...},
{otherStuff...}
]
Why is it not possible to pass "html_col_width" as a parameter?
Since each element of the html_col_width array should be a separate element of the columnDefs array, you can use spread syntax to merge it into the array:
columnDefs: [
... html_col_width,
{ otherstuff...},
{ otherstuff...}
]

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.

How to sort only certain columns

I am using jQuery DataTables plugin to sort table data. I have four columns: Name, Position, Office and Age. What I want is user to be able to sort only Name and Age columns, not all the columns. But I am not able to stop sorting on OTHER columns. Can you please suggest something?
This code disable sorting, 0 - index of column.
For old version
aoColumnDefs: [
{
bSortable: false,
aTargets: [ 0 ]
}
]
for DataTables 1.10+
columnDefs: [
{ orderable: false, targets: 0 }
]
Especially for example, you need this
$(document).ready(function() {
$('#example').dataTable( {
"order": [[ 0, "desc" ]],
"aoColumns": [
null,
{ "bSortable": false },
{ "bSortable": false },
null
]
} );
} );
fiddle

Categories

Resources