DataTables plugin is not working when hiding a details - javascript

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.

Related

jQuery dataTable to show recent records

I'm new to dataTables concept in jQuery. I'm trying my best to learn and work with dataTables. My requirement is to show most recent recent records when the checkbox is checked. I'm using jQuery datatable.
Below is my sample code:
$(document).ready(function() {
initTable();
} );
function initTable(){
oTable = $('#table_id').dataTable({
"aaSorting": [[ 12, "desc" ]],
"oLanguage": {
"sProcessing": "<span style='font-size:20px; color:blue;'>Loading...<span/>",
"sLengthMenu": 'Display <select>'+
'<option value="10">10</option>'+
'<option value="20">20</option>'+
'<option value="30">30</option>'+
'<option value="40">40</option>'+
'<option value="50">50</option>'+
'</select> records'
},
"bProcessing": true,
"bServerSide": true,
"asStripeClasses": [ 'evenrow', 'oddrow' ],
"sAjaxSource": "spreadData.do?method=searchSpreadData",
"fnServerParams": function ( aoData )
{
aoData.push({"name":"searchCriteria.toDate", "value": $('#todateId').attr("value") });
aoData.push( { "name":"searchCriteria.SerialNumber", "value":$('#serialNumberId').attr("value")});
aoData.push( { "name":"searchCriteria.formatId", "value": $('#formatId').attr("value")});
aoData.push( { "name":"searchCriteria.fromDate", "value": $('#fromdateId').attr("value")});
aoData.push( { "name":"searchCriteria.doSearch", "value": $('#doSearchId').attr("value")});
aoData.push( { "name":"searchCriteria.spreadpercentage", "value": $('#spreadPercentage').attr("value")});
},
"aoColumnDefs": [
{ "bVisible": false, "aTargets": [ 0 ] },
{ "bVisible": false, "aTargets": [ 11 ] }
],
"bJQueryUI": true,
"bFilter": false
});
$('#displayRecentRecords').click( function() {
alert("step1");
oTable.fnDraw();
} );
}
//The below function is not getting called when checkbox is checked from UI.
$.fn.dataTableExt.afnFiltering.push(
function( oSettings, aData, iDataIndex ) {
alert("step2");
if($("#displayRecentRecords").is(':checked')){
return true;
}
return !aData[11];
}
);
Show Recent Records:<input type="checkbox" id="displayRecentRecords"/>
Please see my sample code above. When I run the application and select the checkbox step1 alertbox is shown but step2 alert box is not getting called.
Please suggest what are the changes to be done to the above code to call last mentioned datatable function (alertbox which prints step2).
I'm new to dataTable concepts in jQuery. I read the documentation and came across few examples. Please find the JSFiddle : http://jsfiddle.net/9jf2k53p/135/.
Please suggest what modifications to be done in JSFiddle to show the most recent records when the checkbox is checked.
Appreciate the help. Thanks.
Change this line:
$.fn.dataTableExt.afnFiltering.push(
to this:
$oTable.fn.dataTableExt.afnFiltering.push(
OR (not sure which will work in your case):
$oTable.dataTableExt.afnFiltering.push(
You need to define the table as part of this function. That's what the oTable is for, as you defined this variable on the 6th line of your code above.
SOLUTION
You need to define custom filtering function before initializing the table.
$.fn.dataTableExt.afnFiltering.push(
function( oSettings, aData, iDataIndex ){
// ... skipped ...
}
);
var oTable = $('#table_id').dataTable({
// ... skipped ...
});
DEMO
See this jsFiddle for code and demonstration.

Datatables serverside info + static colum with 2 buttons

I'm struggeling to make a static column with 2 buttons that trigger 2 links with dynamic data. I managed to make 1 button work but i can't make the other. I tried adding an id to each one and call different functions for each one but it seems it's only working with $(\'#example tbody \') and not ($(\'#customID \').
Here is my js:
<script type="text/javascript">
$(document).ready(function() {
var table = $(\'#example\').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "app/server_processing.php",
"columnDefs": [ {
"targets": -1,
"data": null,
"defaultContent": "<button>Edit</button> <button>Delete</button>"
} ]
} );
$(\'#example tbody \').on( \'click\', \'button\', function () {
var data = table.row( $(this).parents(\'tr\') ).data();
window.location.href = "index.php?categ=edit&id="+ data[0];
} );
} );
</script>
I fixed it
<script type="text/javascript">
$(document).ready(function() {
var table = $(\'#example\').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "app/server_processing.php",
"columnDefs": [ {
"targets": -1,
"data": null,
"defaultContent": "<button id="edit">Edit</button> <button id="delete">Delete</button>"
} ]
} );
$(\'#example tbody \').on( \'click\', \'#edit\', function () {
var data = table.row( $(this).parents(\'tr\') ).data();
window.location.href = "index.php?categ=edit&id="+ data[0];
} );
$(\'#example tbody \').on( \'click\', \'#delete\', function () {
var data = table.row( $(this).parents(\'tr\') ).data();
window.location.href = "index.php?categ=delete&id="+ data[0];
} );
} );
</script>

How to change value in an xml file onclick using DataTable

I have the following code I have been working on using DataTable. When I click on the ACK button, it updates the DOM but not the xml file. I want it to update the xml file so that anyone else who accesses the site won't have to ACK it again.
Code:
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
var addButton = function(){
$('#alert-table tr td').each(function(){
if($(this).index() == 3 && $(this).html() == "0")
{
$(this).html($('<input type="button" value="ACK" onclick="$(this).parent().html(1);">'));
}
});
}
var refreshAlertTable = $('#alert-table').dataTable( {
"bInfo": false,
"sAjaxSource": 'ajax/alert_json.xml',
"bServerSide": true,
"bJQueryUI": true,
"bLengthChange": false,
"bPaginate": false,
"bFilter": false,
"aaSorting" : [[2, "desc"]],
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
if ( aData[2] == "5" )
{
$('td', nRow).css('background-color', 'Red');
}
else if ( aData[2] == "4" )
{
$('td', nRow).css('background-color', 'Orange');
}
},
"fnDrawCallback": function ( oSettings ) {
addButton();
}
});
setInterval (function() {
refreshAlertTable.fnDraw();
}, 5000);
} );
</script>
Thanks
Check below :
var table1 = $('#youtblename').DataTable();
var pathp = "/server_processing_pie.php";
tablel.clear();
tablel.draw();
tablel.ajax.url(pathp).load();

How to filter OUT specific rows with DataTables

I am using jQuery DataTables and I would like to know how I can filter OUT rows of my table to show and hide them depending on the state of a checkbox. If my 'Hide' checkbox is checked then hide rows where class=var and if checkbox is not checked show rows where class=var
I have setup a small demo with the ability to hide/remove the rows I want but this doesn't allow the rows to reappear.
http://jsfiddle.net/bcraig/cY8Cn/2/
$('#stock').DataTable({
"sDom": '',
"infoEmpty": "No entries to show",
"aaSorting": [ ],
"aoColumnDefs": [{ "bSortable": false, "aTargets": [ 0 ]}],
});
var oTable = $('#stock').DataTable();
$('#hide').click(function() {
if ($(this).is(':checked')) {
oTable.row('.takenstock, .takensold').remove().draw(true);
$('label').text("Show taken");
} else {
oTable.draw();
$('label').text("Hide taken");
}
});
You have to use the DataTables filters, I changed the code to be like below, you can check it in action in fiddle example:
http://jsfiddle.net/cY8Cn/4/
Also here you are the filtering documentation from DataTables:
http://www.datatables.net/development/filtering
$('#stock').DataTable({
"sDom": '',
"infoEmpty": "No entries to show",
"aaSorting": [ ],
"aoColumnDefs": [{ "bSortable": false, "aTargets": [ 0 ]}],
});
var oTable = $('#stock').DataTable();
$.fn.dataTableExt.afnFiltering.push(
function( oSettings, aData, iDataIndex ) {
var nTr = oSettings.aoData[ iDataIndex ].nTr;
if (($(nTr).hasClass('takenstock') || $(nTr).hasClass('takensold'))
&& $('#hide').is(':checked')) {
return false;
}
else {
return true;
}
}
);
$('#hide').click(function() {
oTable.draw();
if ($(this).is(':checked')) {
$('label').text("Show taken");
} else {
$('label').text("Hide taken");
}
});

Javascript conditional formatting not recognized

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
}
}
],
...

Categories