Javascript conditional formatting not recognized - javascript

I'm having a jQuery DataTable that is generated from a JSON file. All works fine, but as it comes to conditional formatting, I get stuck. The following script gives all cells in column 2 a 'positive' class (even negative integers). What's wrong with my if-statement?
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
if ( parseFloat(aData[1]) <= 0 ) {
jQuery('td:eq(1)', nRow).addClass('negative');
} else {
jQuery('td:eq(1)', nRow).addClass('positive');
}
return nRow;
}
thanks in advance!
edit: a part of the JSON file (the number I'm referring to is "punten":
[
{
"spel_id": "2012-09-24 15:43:56",
"locatie": "white room",
"speler": "Arne",
"punten": "17"
},
{
"spel_id": "2012-09-24 15:43:56",
"locatie": "white room",
"speler": "Bjorg",
"punten": "26"
}
]
and my js to generate the table (using DataTables):
$(document).ready( function() {
var oTable = $('#example').dataTable( {
"sAjaxSource": "json_gespeeldekaartings.php",
"aoColumns": [
{ "mData": "kaarting"},
{ "mData": "speler" },
{ "mData": "punten"}
],
"sAjaxDataProp": "",
"sPaginationType": "full_numbers",
"aaSorting": [],
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
if ( parseFloat(aData[1]) <= 0 ) {
jQuery('td:eq(1)', nRow).addClass('negative');
} else {
jQuery('td:eq(1)', nRow).addClass('positive');
}
return nRow;
}
} )
} );

inster of
if ( parseFloat(aData[1]) <= 0 ) {
use
if ( parseFloat(aData.punten <= 0 )
EDIT
try this :
remove fnRowCallback and use mRender for in this example :
...
"aoColumns": [
{ "mData": "kaarting"},
{ "mData": "speler" },
{ "mData": "punten",
"sType": "numeric",
"mRender": function ( data, type, full ) {
if(data > 0) return "<div class='positive'>" + data + "</div>"; // example
return "<div class='negative'>" + data + "</div>"; // example
}
}
],
...

Related

Jquery Datatable not working?

I have created a query table using data from json.
I am trying to combine two column values in one
but i always get undefined data when i try to combine two columns.
I am not sure what is wrong here.
not sure what is wrong here
$("#submit").click(function(){
var dataTableExample = $('#tbl_jad').DataTable();
$('#tbl_jad').show();
if (dataTableExample != 'undefined') {
dataTableExample.destroy();
}
dataTableExample =
$('#tbl_jad').DataTable({
"aaData": data.d.results,
"aoColumns": [
{
"mData": "ID"
},
{
"mData": "Position_x0020_Number",
},
{
"mData": "Title"
}, {
"mData": "Type_x0020_of_x0020_Action"
}, {
"mData": "Series"
}]
,
"columnDefs": [
{
"render": function ( data, type, row ) {
return data +' ('+ row[0]+')';
},
"targets": 1
},
{ "visible": false, "targets": [ 0 ] }
]
});
}
});
return data +' ('+ row["ID"]+')'
where ID is the column heading or column name

Filter Datatables after Ajax call

I'm working in CodeIgniter and i have a DataTable, i want to filter the data from the DT after the ajax has been called. I'm trying to do that by filtering the table, but it's not working.
Here's the JS Code.
$(function () {
var tableRep= $("#tblreport").dataTable({
responsive: true, filter:true, order: [[ 1, "desc" ]],
processing: true, serverSide: true,
ajax: { "url": baseurl+"reports/Report/dataTable", "type": "POST" },
columns:
[
{data:"idReport",},
{data:"date"},
{data:"customer"},
{data:"status",visible:false},
{data:null,searchable:false,orderable: false,width:"120px", render: function (row)
{ if (row.status == "wait") {return '<a class="glyphicon glyphicon-search" data-toggle="modal" data-target="#report">Asign</a>'; }
else if (row.status == "process") {return '<a data-toggle="modal" data-target="#report">Edit</a>';} else return '';} }
],
columnDefs:
[
{ responsivePriority: 1, targets: 1 },
{ responsivePriority: 2, targets: -1 },
{ responsivePriority: 3, targets: 2 }
], fnCreatedRow: function( nRow, aData, iDataIndex ) {
if ( aData["status"] == "ready" ) { $('td', nRow).css('background-color', '#BEF781'); }
else if ( aData["status"] == "wait" ) { $('td', nRow).css('background-color', '#F2F5A9'); }
else { $('td', nRow).css('background-color', '#FFFFFF'); }
}})
});
var filteredData = tableRep.column(4).data().filter( function ( value, index ) {return value!="cancel" ? true : false;} );
Did you try this option?
var tableRep= $("#tblreport").dataTable({
//your config
})
.on('draw.dt', function () {
//Add here yours filters
});

Datatables Format for Currency

I need to format a currency using commas in datatables JSON data. But I have got no luck, Please help me.
The code:
listReportByProductCat(function (json) {
var table = $('#bycat_table').DataTable({
"columnDefs": [
{ "visible": false, "targets": 1 }
{ "column": num-fmt, "targets": 3 } // PROBLEM HERE
],
"order": [[ 1, 'asc' ]],
"displayLength": 25,
"drawCallback": function ( settings ) {
var api = this.api();
var rows = api.rows( {page:'current'} ).nodes();
var last=null;
api.column(1, {page:'current'} ).data().each( function ( group, i ) {
if ( last !== group ) {
$(rows).eq( i ).before(
'<tr class="group"><td colspan="6"><b>'+group+'</b></td></tr>'
);
last = group;
}
} );
},
destroy: true,
processing: true,
data: json,
"columns": [
{ "data": "Prod ID" },
{ "data": "catname" },
{ "data": "Product Name" },
{ "data": "Price" },
{ "data": "Qty" },
{ "data": "Total" }
]
});
So the problem happened on target : 3, I followed datatables doc using num-fmt but still doesn't work. Please help.
follow this link for sorting formatted data
https://datatables.net/plug-ins/sorting/#formatted_numbers
<script type="text/javascript" src="jquery.dataTables.js"></script>
<script type="text/javascript" src="dataTables.numericComma.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#example').dataTable( {
"columnDefs": [
{ "type": "numeric-comma", targets: 3 }
]
} );
} );
</script>

jQuery DataTable Undefined

I have two DataTables defined in $(document).ready() as follows:
oProdTable1 = $('#productstable1').dataTable( {...} );
oProdTable2 = $('#productstable2').dataTable( {...} );
Outside of $(document).ready(), I try to reload them. When I put a breakpoint in the following success function, I find that oProdTable1 is defined, but oProdTable2 is undefined:
function addProduct(productLine) {
$.ajax({
type: "POST",
url: 'ajax-add-product.php',
data: { productLine: productLine},
success: function(data) {
oProdTable1.fnReloadAjax();
oProdTable2.fnReloadAjax();
}
});
}
I can't find a difference between the definitions of these two tables. I also am wondering why oProdTable1 does not need to be declared with "var", yet is defined. Any ideas?
EDIT: I should note that oProdTable1 appears correctly, but oProdTable2 requires me to click to sort by a column for the rows to appear.
EDIT2: I have tried putting addProduct() inside $(document).ready(). oProdTable1 is still undefined and oProdTable2 is still undefined. I tried putting oProdTable2 before oProdTable1 and now oProdTable1 doesn't even load and both tables are undefined!
EDIT3: Every DataTable in the code after oProdTable2 does not load and is undefined. I compared the oProdTable1 and oProdTable2 code using the Notepad++ compare plugin and cannot find any major differences such as missing braces that I think could cause this.
EDIT4: Here is the code for oProdTable2, which seems to be problematic:
oProdTable2 = $('#productstable2').dataTable( {
"aaSorting": [[ 1, "asc" ]],
"aoColumnDefs":[
{"aTargets":[0],"bSearchable":false,"bVisible": false},
{"aTargets":[1],"sWidth":"60px"},
{"aTargets":[2],"sWidth":"200px"},
{"aTargets":[3],"sWidth":"300px"},
{"aTargets":[4],"sWidth":"60px"},
{"aTargets":[5],"sWidth":"60px"},
{"aTargets":[6],"sWidth":"60px"},
{"aTargets":[7],"sWidth":"60px"},
{"aTargets":[8],"sWidth":"60px"},
{"aTargets":[9],"sWidth":"60px"},
{"aTargets":[10],"sWidth":"60px"},
{"aTargets":[11],"sWidth":"60px"},
{ "sClass": "usa", "aTargets": [ 4, 5 ] },
{ "sClass": "can", "aTargets": [ 6, 7 ] },
{ "sClass": "lat", "aTargets": [ 8, 9 ] },
],
"iDisplayLength": 100, //sets item limit for table
"bJQueryUI": true,
"bProcessing": true,
"bServerSide": true,
"bSortCellsTop": true,
//"bStateSave": true,
"bSortClasses": false,
"sDom": 'T<"clear">C<"fg-toolbar ui-widget-header ui-corner-tl ui-corner-tr ui-helper-clearfix"lfr>t<"fg-toolbar ui-widget-header ui-corner-bl ui-corner-br ui-helper-clearfix"ip>',
"oTableTools": {
"sRowSelect": "single",
"sSwfPath": "/swf/copy_cvs_xls_pdf.swf",
"aButtons":
[
//"Add Product" button
{
"sExtends": "text",
"sButtonText": "Add Product",
"fnClick": function ( nButton, oConfig, oFlash ) {
addProduct("2");
}
},
{
"sExtends": "collection",
"sButtonText": "Export",
"aButtons": [ "copy","print","csv", "xls", "pdf" ]
}
]
},
'sAjaxSource': 'ajax-getproductstable.php',
"fnServerParams": function ( aoData ) {
aoData.push( { "name": "productLine", "value": "2" } );
},
"fnInitComplete": function() {
var oSettings = $('#productstable2').dataTable().fnSettings();
for ( var i=0 ; i<oSettings.aoPreSearchCols.length ; i++ ){
if(oSettings.aoPreSearchCols[i].sSearch.length>0){
$("thead input")[i-1].value = oSettings.aoPreSearchCols[i].sSearch;
$("thead input")[i-1].className = "activefilter"; }
}
},
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
var id = aData[0];
$(this.fnGetTds(nRow)[1]).addClass("editable").addClass("ref");
$(this.fnGetTds(nRow)[2]).addClass("edit_area").addClass("name");
$(this.fnGetTds(nRow)[3]).addClass("edit_area").addClass("description");
$(this.fnGetTds(nRow)[4]).addClass("editable").addClass("price_rtl_usa");
$(this.fnGetTds(nRow)[5]).addClass("editable").addClass("price_dlr_usa");
$(this.fnGetTds(nRow)[6]).addClass("editable").addClass("price_rtl_can");
$(this.fnGetTds(nRow)[7]).addClass("editable").addClass("price_dlr_can");
$(this.fnGetTds(nRow)[8]).addClass("editable").addClass("price_rtl_lat");
$(this.fnGetTds(nRow)[9]).addClass("editable").addClass("price_dlr_lat");
$(this.fnGetTds(nRow)[10]).addClass("editable").addClass("ins_val_rtl_usa");
$(this.fnGetTds(nRow)[11]).addClass("editable").addClass("ins_val_dlr_usa");
$(this.fnGetTds(nRow)[12]).addClass("editable").addClass("ins_val_rtl_can");
$(this.fnGetTds(nRow)[13]).addClass("editable").addClass("ins_val_dlr_can");
$(this.fnGetTds(nRow)[14]).addClass("editable").addClass("net_l");
$(this.fnGetTds(nRow)[15]).addClass("editable").addClass("net_w");
$(this.fnGetTds(nRow)[16]).addClass("editable").addClass("net_h");
$(this.fnGetTds(nRow)[17]).addClass("editable").addClass("net_weight");
$(this.fnGetTds(nRow)[18]).addClass("editable").addClass("packed_l");
$(this.fnGetTds(nRow)[19]).addClass("editable").addClass("packed_w");
$(this.fnGetTds(nRow)[20]).addClass("editable").addClass("packed_h");
$(this.fnGetTds(nRow)[21]).addClass("editable").addClass("packed_weight");
$(this.fnGetTds(nRow)[22]).addClass("editable").addClass("customs_cost");
$(this.fnGetTds(nRow)[23]).addClass("editable").addClass("customs_desc");
$(this.fnGetTds(nRow)[24]).addClass("editable").addClass("customs_code");
$(this.fnGetTds(nRow)[25]).addClass("editable").addClass("customs_origin");
$(this.fnGetTds(nRow)[26]).addClass("edit_area").addClass("note");
$(nRow).attr("id", id);
return nRow;
},
"fnDrawCallback": function () {
// CODE FOR EDITABLE INLINES
$(".edit_area_w").editable('ajax-edit-product-inline.php', {
type : 'mce',
submit : 'OK',
indicator : "Saving...",
tooltip : 'Click to edit...',
width : '500px',
height : '100px',
"callback": function( sValue, y ) {
$(this).removeClass('empty_edit');
$("#productstable tr").removeClass("just_edited");
$(this).parent().addClass("just_edited");
var aPos = oProdTable2.fnGetPosition( this );
var update = oProdTable2.fnUpdate( sValue, aPos[0], aPos[2], true, true);
},
"submitdata": function ( value, settings ) {
return {
"row_id": this.parentNode.getAttribute('id'),
"column": oProdTable2.fnGetPosition( this )[2]
};
}
});
$('.editable').editable('ajax-edit-product-inline.php', {
event : "dblclick",
"callback": function( sValue, y ) {
$(this).removeClass('empty_edit');
$("#productstable tr").removeClass("just_edited");
$(this).parent().addClass("just_edited");
var aPos = oProdTable2.fnGetPosition( this );
var update = oProdTable2.fnUpdate( sValue, aPos[0], aPos[2], true, true);
},
"submitdata": function ( value, settings ) {
return {
"row_id": this.parentNode.getAttribute('id'),
"column": oProdTable2.fnGetPosition( this )[2]
};
},
"height": "14px"
} );
$('.edit_area').editable('ajax-edit-product-inline.php', {
event : "dblclick",
type : "textarea",
cancel : 'Cancel',
submit : 'OK',
indicator : '<img src="img/indicator.gif">',
"callback": function( sValue, y ) {
$(this).removeClass('empty_edit');
$("#productstable tr").removeClass("just_edited");
$(this).parent().addClass("just_edited");
var aPos = oProdTable2.fnGetPosition( this );
oProdTable2.fnUpdate( sValue, aPos[0], aPos[2]);
},
"submitdata": function ( value, settings ) {
return {
"row_id": this.parentNode.getAttribute('id'),
"column": oProdTable2.fnGetPosition( this )[2]
};
},
} );
$('.edit_select').editable('ajax-edit-product-inline.php', {
event : "dblclick",
loaddata: function ( value, settings ) {
return {
"pid": $(this).parent().attr("id")
};
},
loadurl : 'ajax-part-selects.php',
loadtype: "GET",
type : 'select',
submit : 'OK',
"callback": function( sValue, y ) {
$(this).removeClass('empty_edit');
$("#productstable tr").removeClass("just_edited");
$(this).parent().addClass("just_edited");
var aPos = oProdTable2.fnGetPosition( this );
oProdTable2.fnUpdate( sValue, aPos[0], aPos[2]);
},
"submitdata": function ( value, settings ) {
return {
"row_id": this.parentNode.getAttribute('id'),
"column": oProdTable2.fnGetPosition( this )[2]
};
},
});
}
} );
$("#productstable2 .floating_filters input").keyup( function () {
// Filter on the column (the index) of this element
oProdTable2.fnFilter( this.value, $(".floating_filters input").index(this)+1 );
$(this).addClass("activefilter");
} );
$("#productstable2 .floating_filters input").each( function (i) {
asInitVals[i] = this.value;
} );
$("#productstable2 .floating_filters input").focus( function () {
if ( $(this).hasClass("search_init"))
{
this.className = "";
this.value = "";
}
} );
$("#productstable2 .floating_filters input").blur( function (i) {
if ( this.value == "" )
{
$(this).removeClass("activefilter");
$(this).addClass("search_init");
this.value = asInitVals[$(".floating_filters input").index(this)];
}
} );
I finally found the solution! The problem wasn't even with the javascript code, it was with the html. The table with the id "productstable2" had one less "td" than "th". I just needed to add an additional <td></td> to the list of "td"s.

DataTables plugin is not working when hiding a details

I am using the DataTables jQuery plugin and I am having a problem when I want to insert a hide details option on my existing table, this is how this option should look like: LINK
My problem is that table head is inserted correctly but I am not seeing a table column with plus sign to expand and see details.
Here is my code and as you can see it is almost incidental as it is on the link that I provided.
The code:
/* Formating function for row details */
function fnFormatDetails ( oTable, nTr )
{
var aData = oTable.fnGetData( nTr );
var sOut = '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">';
sOut += '<tr><td>Rendering engine:</td><td>'+aData[1]+' '+aData[4]+'</td></tr>';
sOut += '<tr><td>Link to source:</td><td>Could provide a link here</td></tr>';
sOut += '<tr><td>Extra info:</td><td>And any further details here (images etc)</td></tr>';
sOut += '</table>';
return sOut;
}
$(document).ready(function() {
/*
* Insert a 'details' column to the table
*/
var nCloneTh = document.createElement( 'th' );
var nCloneTd = document.createElement( 'td' );
nCloneTd.innerHTML = '<img src="../images/details_open.png">';
nCloneTd.className = "center";
$('#jphit thead tr').each( function () {
this.insertBefore( nCloneTh, this.childNodes[0] );
} );
$('#jphit tbody tr').each( function () {
this.insertBefore( nCloneTd.cloneNode( true ), this.childNodes[0] );
} );
var oTable=$('#jphit').dataTable( {
"sDom": 'T,C<"clear">lfrtip',
"oTableTools": {
"sSwfPath": "swf/copy_csv_xls_pdf.swf"
},
"oColVis": {
"buttonText": "Extend table",
"activate": "mouseover"
},
"aoColumnDefs": [
{ //"bVisible": false, "aTargets": [ 0 ],
"bSortable": false, "aTargets": [ 0 ] }
],
"aaSorting": [[1,'asc']],
"bProcessing": true,
"bServerSide": true,
"sPaginationType": "full_numbers",
"sScrollY": "350px",
"bDeferRender": true,
"sAjaxSource": "increment_table.php"
} );
/* Add event listener for opening and closing details
* Note that the indicator for showing which row is open is not controlled by DataTables,
* rather it is done here
*/
$('#jphit tbody td img').live('click', function () {
var nTr = $(this).parents('tr')[0];
if ( oTable.fnIsOpen(nTr) )
{
/* This row is already open - close it */
this.src = "../images/details_open.png";
oTable.fnClose( nTr );
}
else
{
/* Open this row */
this.src = "../images/details_close.png";
oTable.fnOpen( nTr, fnFormatDetails(oTable, nTr), 'details' );
}
} );
} );
As I was debugging I realized that this code is processed but its not drawing what it should draw:
$('#jphit tbody tr').each( function () {
this.insertBefore( nCloneTd.cloneNode( true ), this.childNodes[0] );
} );
Any idea what might went wrong with my code? And if someone is using this plugin can you please help and share your experience?
EDIT:
This is the picture that I am getting. It should be shifted one spot to the right and in that empty column I should have a pic for opening a details
EDIT2:
I have tried to use this code with data that I wrote manually inside the table and it is working perfectly.
I have tired to put the code inside the fnDrawCallback function but then I have 2 headers as my table is drawing twice.
How to use this with sAjaxSource?
var oTable = $('#jphit').dataTable( {
"sDom": 'T,C<"clear">lfrtip',
"oTableTools": {
"sSwfPath": "swf/copy_csv_xls_pdf.swf"
},
"oColVis": {
"buttonText": "Extend table",
"activate": "mouseover"
},
"aoColumnDefs": [
{ //"bVisible": false, "aTargets": [ 0 , 2 ] ,
"bSortable": false, "aTargets": [ 0 ] }
],
"bProcessing": true,
//"bServerSide": true,
"sPaginationType": "full_numbers",
"sScrollY": "350px",
"bDeferRender": true,
//"sAjaxSource": "live_table.php",
"fnDrawCallback": function( oSettings ) {
var nCloneTh = document.createElement( 'th' );
var nCloneTd = document.createElement( 'td' );
nCloneTd.innerHTML = '<img src="images/details_open.png" style="width:25px; height:25px;">';
nCloneTd.className = "center";
$('#jphit thead tr').each( function () {
this.insertBefore( nCloneTh, this.childNodes[0] );
} );
$('#jphit tbody tr').each( function () {
this.insertBefore( nCloneTd, this.childNodes[0] );
} );
}
} );
The problem here is that table renders data based on data from response. I suppose that there is aaData array where 0 index is filled with value, which is inserted in the first column as expected.
You can use this approach http://datatables.net/release-datatables/examples/ajax/null_data_source.html
In your case you could change aoColumnDefs option to:
"aoColumnDefs": [ {
"bSortable": false, mData : null, "aTargets": [ 0 ]
}],
EDIT Override fnServerData
The other idea I have is to override fnServerData callback, to change datasource as you need.
"fnServerData": function ( sSource, aoData, fnCallback, oSettings ) {
oSettings.jqXHR = $.ajax( {
"dataType": 'json',
"type": "POST",
"url": sSource,
"data": aoData,
"success": function(jsonData) {
//Here you need to shift jsonData aoData array values to right
//to add [0] index in all values.
//I have no possibility to test it today:( but hope it will help you
//and Then you need to call fnCallback(jsonData) with changed jsonData
for (var data in jsonData["aoData"]) {
jsonData["aoData"][data].unshift(0);
}
fnCallback(jsonData);
}
} );
}
Hope it helps.

Categories