Datatable tr click function - javascript

I want to do some operations after clicking a particular row. I followed the API and this is what I ended up with but the click event is not working.
$(document).ready(function() {
table = $('#employees').dataTable( {
"bJQueryUI": true,
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "show_employee_processor.php",
"aoColumns": [
{ "sTitle": "Empoyee ID" },
{ "sTitle": "Last Name" },
{ "sTitle": "First Name" },
{ "sTitle": "BBan Number" },
]
} );
table.$('tr').click(function() {
var data = table.fnGetData( this );
alert(data);
});
} );
The datatable is getting drawn but the click event is not working. What am I missing?

try delegated event:
table.on('click','tr',function() {
var data = table.fnGetData( this );
alert(data);
});
or:
$('#employees').on('click','tr',function() {
var data = table.fnGetData( this );
alert(data);
});

$("#employees tr").click( function( e ) {
if ( $(this).hasClass('row_selected')==false ) {
table .$('tr.row_selected').removeClass('row_selected');
$(this).addClass('row_selected');
var data = table.fnGetData( this );
alert(data);
}
else{
$(this).removeClass('row_selected');
}
});
CSS>
#employees tr.row_selected{
background-color:#B5CCD2;
opacity:0.95;
font-weight:bold;
}

Related

datatables default regex to search only start

Hi have the java script for datatables as below, How can define it so that the search is done only for start values, eg : [ hello, hello_all, all_hello] is there and my search key word is "hel" i should get filter of [hello,hello_all].
$('#example').DataTable( {
data: new_data,
dom: '<"top"fB>rt<"bottom"ipl>',
buttons:['csv'],
search :{"bSmart": false,
"regex":true},
columns: [
{ title: "Action" },
{ title: "Input" },
{ title: "State" },
{ title: "Completed" },
{ title: "Project" },
],
"order": [[ 3, "desc" ]]
});
See the documentation:
https://datatables.net/examples/api/regex.html
The filterColumn function is what you looking for I think.
I hope that helps.
Gruesse
function filterGlobal () {
$('#example').DataTable().search(
$('#global_filter').val(),
$('#global_regex').prop('checked'),
$('#global_smart').prop('checked')
).draw();
}
function filterColumn ( i ) {
$('#example').DataTable().column( i ).search(
$('#col'+i+'_filter').val(),
$('#col'+i+'_regex').prop('checked'),
$('#col'+i+'_smart').prop('checked')
).draw();
}
$(document).ready(function() {
$('#example').DataTable();
$('input.global_filter').on( 'keyup click', function () {
filterGlobal();
} );
$('input.column_filter').on( 'keyup click', function () {
filterColumn( $(this).parents('tr').attr('data-column') );
} );
} );
I have a separate search field for one of the columns and here's my solution for begins-with search:
vm.searchForLocation = function() {
vm.dtInstance.DataTable.column(2)
.search("^"+vm.locationCode, true, false )
.draw();
}

Why would blur event only fire one time? [duplicate]

I have a couple of drop downs that are populated from SharePoint using SPServices. This part works great. But then, I have a button that on click loads data from SharePoint and uses the dropdown texts as filter to fetch the data that will populate a table using the DataTables plugin. This part works only once; if I click the button again, nothing happens.
This is how I populate the dropdowns:
$(document).ready(function () {
var theYear; // Selected Year
var theRO; // Selected RO
//Fills the Dropdown lists (Year and RO)
$().SPServices({
operation: "GetListItems",
async: false,
listName: "{ListID}",
CAMLViewFields: "<ViewFields><FieldRef Name='Fiscal_x0020_Year' /><FieldRef Name='Regional_x0020_Office' /></ViewFields>",
completefunc: function (xData, Status) {
//Add Select Value option
$("#dropdown").prepend($('<option>', {
value: '',
text: 'Select Fiscal Year'
}));
$("#dropdownRO").prepend($('<option>', {
value: '',
text: 'Select Regional Office'
}));
//Fetching Data from SharePoint
$(xData.responseXML).SPFilterNode("z:row").each(function () {
var dropDown = "<option value='" + $(this).attr("ows_Fiscal_x0020_Year") + "'>" + $(this).attr("ows_Fiscal_x0020_Year") + "</option>";
var dropDownRO = "<option value='" + $(this).attr("ows_Regional_x0020_Office") + "'>" + $(this).attr("ows_Regional_x0020_Office") + "</option>";
$("#dropdown").append(dropDown);
$("#dropdownRO").append(dropDownRO);
/////////////Deletes duplicates from dropdown list////////////////
var usedNames = {};
$("#dropdown > option, #dropdownRO > option").each(function () {
if (usedNames[this.text]) {
$(this).remove();
} else {
usedNames[this.text] = this.value;
}
});
////Deletes repeated rows from table
var seen = {};
$('#myTable tr, #tasksUL li, .dropdown-menu li').each(function () {
var txt = $(this).text();
if (seen[txt]) $(this).remove();
else seen[txt] = true;
});
});
} //end of completeFunc
}); //end of SPServices
$('.myButton').on('click', function () {
run()
});
}); //End jQuery Function
This is the function I need to run every time I click on "myButton" after changing my selection in the dropdowns:
function run() {
theYear = $('#dropdown option:selected').text(); // Selected Year
theRO = $('#dropdownRO option:selected').text(); // Selected RO
var call = $.ajax({
url: "https://blah-blah-blah/_api/web/lists/getByTitle('Consolidated%20LC%20Report')/items()?$filter=Fiscal_x0020_Year%20eq%20'" + theYear + "' and Regional_x0020_Office eq '" + theRO + "'&$orderby=Id&$select=Id,Title,Fiscal_x0020_Year,Notices_x0020_Received,Declined_x0020_Participation,Selected_x0020_Field_x0020_Revie,Selected_x0020_File_x0020_Review,Pending,Pending_x0020_Previous_x0020_Yea,Controversial,GFP_x0020_Reviews,NAD_x0020_Appeals,Mediation_x0020_Cases,Monthly_x0020_Cost_x0020_Savings,Monthly_x0020_Expenditure,Regional_x0020_Office,Month_Number", //Works, filters added
type: "GET",
cache: false,
dataType: "json",
headers: {
Accept: "application/json;odata=verbose",
}
}); //End of ajax function///
call.done(function (data, textStatus, jqXHR) {
var oTable = $('#example').dataTable({
"aLengthMenu": [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
"iDisplayLength": -1, //Number of rows by default. -1 means All Records
"sPaginationType": "full_numbers",
"aaData": data.d.results,
"bJQueryUI": false,
"bProcessing": true,
"aoColumns": [{
"mData": "Id",
"bVisible": false
}, //Invisible column
{
"mData": "Title"
}, {
"mData": "Notices_x0020_Received"
}, {
"mData": "Declined_x0020_Participation"
}, {
"mData": "Selected_x0020_Field_x0020_Revie"
}, {
"mData": "Selected_x0020_File_x0020_Review"
}, {
"mData": "Pending"
}, {
"mData": "Pending_x0020_Previous_x0020_Yea"
}, {
"mData": "Controversial"
}, {
"mData": "GFP_x0020_Reviews"
}, {
"mData": "NAD_x0020_Appeals"
}, {
"mData": "Mediation_x0020_Cases"
}, {
"mData": "Monthly_x0020_Cost_x0020_Savings",
"fnRender": function (obj, val) {
return accounting.formatMoney(val);
}
}, {
"mData": "Monthly_x0020_Expenditure",
"fnRender": function (obj, val) {
return accounting.formatMoney(val);
}
}],
"bDeferRender": true,
"bRetrieve": true,
"bInfo": true,
"bAutoWidth": true,
"bDestroy": true,
"sDom": 'T&;"clear"&;frtip',
"oTableTools": {
"aButtons": ["xls"],
"sSwfPath": "../../Style Library/js/datatables/TableTools/media/swf/copy_csv_xls_pdf.swf",
},
"sSearch": "Filter",
"fnDrawCallback": function () {
//Add totals row
var Columns = $("#example > tbody").find("> tr:first > td").length;
$('#example tr:last').after('<tr><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td></tr>');
//Formating the Total row number to no decimals
$("#example tr:last td:not(:first,:last)").text(function (i) {
var t = 0;
$(this).parent().prevAll().find("td:nth-child(" + (i + 2) + ")").each(function () {
t += parseFloat($(this).text().replace(/[\$,]/g, '') * 1);
});
return parseInt(t * 100, 10) / 100;
});
//Format the monthly expenditure and savings to currency formatFormating the currency
var cell = new Array();
cell[0] = $('#example tr:last td:nth-child(12)').text();
cell[1] = $('#example tr:last td:nth-child(13)').text();
$('#example tr:last').find('td:nth-child(12)').html(accounting.formatMoney(cell[0]));
$('#example tr:last').find('td:nth-child(13)').html(accounting.formatMoney(cell[1]));
$('#example tr:last').find('td:last').hide();
} //hides extra td that was showing
}); //End of Datatable()
}); //End of call.done function
$('#theTableDiv').slideDown();
} //end of run() function
I'm not a programmer, I'm just trying to learn. I would appreciate any help. Thanks in advance
I would guess that you are replacing the part of the page where the button lives. (you really need to format your code more neatly for SO... use JSFiddle.net and their TidyUp button).
If that is the case you need to use a delegated event handler:
$(document).on('click', '.myButton', function () {
run()
});
This listens at a static ancestor of the desired node, then runs the selector when the event occurs, then it applies the function to any matching elements that caused the event.
document is the fallback parent if you don't have a convenient ancestor. Do not use 'body' for delegated events as it has odd behaviour.

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>

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