DataTables combine FooterCallback and select filtering - javascript

Good evening.
I had some problems combining two DataTables functions (see title).
This (FooterCallback) to display the sum of a column with numeric values:
$(document).ready(function() {
$('#pr_table').DataTable( {
"footerCallback": function ( row, data, start, end, display ) {
var api = this.api(), data;
// Remove the formatting to get integer data for summation
var intVal = function ( i ) {
return typeof i === 'string' ?
i.replace(/[\$,]/g, '')*1 :
typeof i === 'number' ?
i : 0;
};
// Total over all pages
total = api
.column( 4 )
.data()
.reduce( function (a, b) {
return intVal(a) + intVal(b);
}, 0 );
// Total over this page
pageTotal = api
.column( 4, { page: 'current'} )
.data()
.reduce( function (a, b) {
return intVal(a) + intVal(b);
}, 0 );
// Update footer
$( api.column( 4 ).footer() ).html(
'cub.m'+pageTotal +' ( cub.m'+ total +' total)'
);
}
} );
} );
With this (select filtering):
$(document).ready(function() {
$('#pr_table').DataTable( {
"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.header()).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>' )
} );
} );
}
} );
} );
If I use only one of the functions in my script, everything is working just fine. But trying to combine them results in DataTables failing to initialize at all (just raw html table shows up).
I am relatively unfamiliar with javascript this advanced, so it would help me if someone would give me an example of the script with a little explanation how to use multiple functions in one initialization.

Related

Javascript Datatable Time Sum

I'm trying to do something with JavaScript DataTable but I'm stuck somewhere .
There are 2 DataTable on the same page .
I am sending data from the first DataTable second DataTable . I can write in the footer section that collects in the second DataTable int .
I collect information on hours in a second column in the DataTable I want to write a footer . I could not do it.
How do you think I should proceed . Existing employees script below.
Thank you to everyone.
<script type="text/javascript" language="javascript">
$(document).ready(function() {
var t = $('#FlowList').DataTable({
rowReorder: true,
"footerCallback": function ( row, data, start, end, display ) {
var api = this.api(), data;
// Remove the formatting to get integer data for summation
var intVal = function ( i ) {
return typeof i === 'string' ?
i.replace(/[\$,]/g, '')*1 :
typeof i === 'number' ?
i : 0;
};
// Tüm sayfaların toplamı
total = api
.column( 3 )
.data()
.reduce( function (a, b) {
return intVal(a) + intVal(b);
}, 0 );
// Gösterilen sayfanın toplamı
pageTotal = api
.column( 3, { page: 'current'} )
.data()
.reduce( function (a, b) {
return intVal(a) + intVal(b);
}, 0 );
// Footer Güncelleme
$( api.column( 3 ).footer() ).html(
/* '$'+pageTotal +' ( $'+ total +' Toplam)' */
'Toplam ' + total
);
}
});
var counter = 1;
var table = $('#NewsListTable').DataTable();
$('#NewsListTable tbody').on('dblclick', 'tr', function(){
var data = table.row( this ).data();
//alert(data[3]);
t.row.add( [
counter +'', //Sıra numarasını her seferinde 1 arttırıyoruz.
data[1],
data[2],
data[3],
data[4],
data[5],
data[6],
data[7],
data[8]
]
).draw( false );
counter++;
});
});
</script>

How to filter through column datatable which has more than one value in column?

I have datatable in my code where user_email column has values like
<td><label>ad#abc.com</label>
<label>ad2#abc.com</td></label>
and another column of hotels like
<td>
<label>abd</label><br/>
<label>bbd</label>
</td>
i want to add filter of each column but want to filter like single values i had define datatable like this
$('#example2').DataTable( {
initComplete: function () {
var i = 0;
this.api().columns().every(function () {
var column = this;
var select = $('<select><option value="0">All</option></select>')
.insertBefore('table')
.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>' )
} );
});
}
} );
So guys can you suggest me how to do this.here is my demo:http://jsfiddle.net/qmzd0u5n/5/

R datatable rowCallback with DT

I am trying to perform two distinct formatting operations on a datatable object using the DT and magrittr packages. One uses the helper function formatRound() and the other is passed in as JavaScript to a rowCallback option in the datatable function.
When I run either of the formatting operations individually the datatable renders with the expected formatting. However, when I run both together the datatable renders blank but I do not get an error.
This code shows the behavior I am describing.
library(magrittr)
library(DT)
df = data.frame(matrix(rnorm(20), nrow=10))
datatable(
data = df
) %>%
formatRound(c("X1", "X2"), 1)
#table renders as expected
datatable(
data = df,
options = list(
rowCallback = JS("
function( row, data, index ) {
if ( index > 2 ) {
$(row).css('background-color', '#EDEDED');
}
else if ( index > 0 ) {
$(row).css('background-color', '#DEDEDE');
}
else {
$(row).css('background-color', '#D3D3D3');
}
}"
)
)
)
#table renders as expected
datatable(
data = df,
options = list(
rowCallback = JS("
function( row, data, index ) {
if ( index > 2 ) {
$(row).css('background-color', '#EDEDED');
}
else if ( index > 0 ) {
$(row).css('background-color', '#DEDEDE');
}
else {
$(row).css('background-color', '#D3D3D3');
}
}"
)
)
) %>%
formatRound(c("X1", "X2"), 1)
#table renders as blank but with no error returned
If you have a look at the JS function of your third attempt in the browser's JS console(click on "Inspect Element option in browser"), it shows up an error saying that 'var' is unidentified because it is outside the scope of the JS function:
(
var d = parseFloat(data[1]); $(this.api().cell(row, 1).node()).html(isNaN(d) ? '' : d.toFixed(1));
var d = parseFloat(data[2]); $(this.api().cell(row, 2).node()).html(isNaN(d) ? '' : d.toFixed(1));
function( row, data, index ) {
if ( index > 2 ) {
$(row).css('background-color', '#EDEDED');
}
else if ( index > 0 ) {
$(row).css('background-color', '#DEDEDE');
}
else {
$(row).css('background-color', '#D3D3D3');
}
})
If you put those two lines inside the JS function, it works perfectly.
You can find the updated code below.
datatable(
data = df,
options = list(
rowCallback = JS("
function( row, data, index ) {
var d = parseFloat(data[1]);
$(this.api().cell(row, 1).node()).html(isNaN(d) ? '' : d.toFixed(1));
var d = parseFloat(data[2]);
$(this.api().cell(row, 2).node()).html(isNaN(d) ? '' : d.toFixed(1));
if ( index > 2 ) {
$(row).css('background-color', '#EDEDED');
}
else if ( index > 0 ) {
$(row).css('background-color', '#DEDEDE');
}
else {
$(row).css('background-color', '#D3D3D3');
}
}"
)
)
)

How to remove columns in JQuery Datatables?

I want to remove the columns which have total = 0.
So I've tried in different ways.
First, I assigned ID to all columns, for example; every <td> is of column will have their ID eg: First columns <td ID = 'col_1'> , second column all <td ID = 'col_2'> etc. And then in when footer callback I've tried to remove if this column total is ZERO then this $("col_"+i).remove(); this code removed table headers only so I've tried again with $("col_"+i).empty() but again it's just empty. <th> only
Then I've tried to hide the columns by creating dynamic but I don't get any values.
"footerCallback": function ( row, data, start, end, display )
{
var api = this.api(), data;
var intVal = function ( i ) { return typeof i === 'string' ? i.replace(/[\$,]/g, '')*1 : typeof i === 'number' ? i : 0;};
var col_gonna_invis = '[';
for(i=1;i<length_of_coloumns;i++)
{
total_salary = api.column( i ).data().reduce( function (a, b) {return intVal(a) + intVal(b);},0 );
$('#total_cont_'+i).html(total_salary);
if(total_salary == 0)
{
col_gonna_invis += '{"targets": [ '+i+' ], "visible": false, "searchable": false },';
}
}
col_gonna_invis += ']';alert(col_gonna_invis);
},
"aoColumnDefs": col_gonna_invis;
Please someone help me fix this issue or please someone tell me how to hide or remove columns which footer total is 0.
Thank you in advance.
I will suggest you use the visible() API method along with the sum() plugin :
Enhance the API with a column().sum() method :
jQuery.fn.dataTable.Api.register( 'sum()', function ( ) {
return this.flatten().reduce( function ( a, b ) {
if ( typeof a === 'string' ) {
a = a.replace(/[^\d.-]/g, '') * 1;
}
if ( typeof b === 'string' ) {
b = b.replace(/[^\d.-]/g, '') * 1;
}
return a + b;
}, 0 );
} );
now, in initComplete() you can very easy hide columns which have a total or sum() of 0 :
var table = $('#example').dataTable({
//...
initComplete : function() {
var api = this.api(),
colCount = api.row(0).data().length;
for (var i=0; i<colCount; i++) {
if (api.column(i).data().sum() == 0) {
api.column(i).visible(false);
}
}
}
});
demo -> http://jsfiddle.net/qer7e5os/

columnfilterwidget in Datatables Filter sort issue

I am using DataTables 1.10 with Columnfilterwidget,
Problem i am facing is
I have values like
0,1.44,10,100,100.00,20,20.13
Right now Columnfilterwidget is sorting these values alphabetically
0
1.44
10
100
100.00
20
20.13
But i want them to be filtered numerically
0
1.44
10
20
20.13
100
100.00
Like this,
This is what i have tried so far
In Columnfilterwidget.js file
ColumnFilterWidget.prototype.fnDraw = function() {
var widget = this;
var oDistinctOptions = {};
var aDistinctOptions = [];
var aData;
if ( widget.asFilters.length === 0 ) {
// Find distinct column values
aData = widget.oDataTable.fnGetColumnData( widget.iColumn );
$.each( aData, function( i, sValue ) {
var asValues = widget.sSeparator ? sValue.split( new RegExp( widget.sSeparator ) ) : [ sValue ];
$.each( asValues, function( j, sOption ) {
if ( !oDistinctOptions.hasOwnProperty( sOption ) ) {
oDistinctOptions[sOption] = true;
aDistinctOptions.push( sOption );
}
} );
} );
// Build the menu
widget.$Select.empty().append( $( '<option></option>' ).attr( 'value', '' ).text( widget.oColumn.sTitle ) );
// aDistinctOptions.sort();
aDistinctOptions.sort(function(a,b){return a - b});
$.each( aDistinctOptions, function( i, sOption ) {
var sText;
if(sOption==='')
sText = $( '<div> (Blank )</div>' ).text();
else
sText = $( '<div>' + sOption + '</div>' ).text();
widget.$Select.append( $( '<option></option>' ).attr( 'value', sOption ).text( sText ) );
} );
if ( aDistinctOptions.length > 1 ) {
// Enable the menu
widget.$Select.attr( 'disabled', false );
} else {
// One option is not a useful menu, disable it
widget.$Select.attr( 'disabled', true );
}
}
};
I changed sort function to numeric, but how can i identify the coming value is numeric, also i checked sValue values are string, so is there any way i can define Columns i want to numeric.
Also tried setting options oColumnFilterWidgets still it didn't worked.
oColumnFilterWidgets: {
"aiExclude": [ 0, 1, 10 ],
"aoColumnDefs": [
// { "bSort": false, "sSeparator": " / ", "aiTargets": [ 5 ] },
{ "fnSort": function( a, b ) { return a-b; }, "aiTargets": [6] },
{"sType": "numeric", "aiTargets":[6]}
]
},
What am i doing wrong here?
Thanks to cyberhobo who fixed this issue.
[https://github.com/cyberhobo/ColumnFilterWidgets/commit/01efef439c557154bad3d61aa00d47285b6d21d6#diff-72250e81389e20ff2fa22ff884fcb6aaR309][1]
Just made the changes he highlighted inside plugin and
"oColumnFilterWidgets": {
"aoColumnDefs": [
{ "bSort": false, "sSeparator": " / ", "aiTargets": [ 2 ] },
{ "fnSort": function( a, b ) { return a-b; }, "aiTargets": [ 3 ] }
]
}
Hope this helps.

Categories

Resources