datatables columnDefs not working: jquery / javascript - javascript

My datatable loads perfectly except the columndefs do not work.
Anybody got a clue?
Please help. I just want to add a click event to every cell in column 1. I get no errors either.
It works in this example on the end column...https://datatables.net/examples/ajax/null_data_source.html
var table = $mytable.DataTable( {
"serverSide": true,
"ajax": {
"url": url_string,
"cache": true,
"columnDefs": [
{"targets": 1,"data": null,"defaultContent": "<button>Select Image ID</button>"} ,
]
},
});

Found a great post on stack overflow that really helped.
and changed it to suit me this is the post Edit jQuery Datatable fields
And here is what I have working for me. I was concentrating too much on the API and less on just Jquery. The trick was execute the jquery after "drawCallback":
Credit to #Jeromy French
var table = $spr_cnt_tbl.DataTable( {
"serverSide": true,
"ajax": {
"url": url_string,
"cache": true,
"columnDefs": [
{"targets": 1,"data": null,"defaultContent": "<button>Select Image ID</button>"} ,
]
},
"drawCallback": function( settings ) {
apply_label();
}
});
var apply_label=function(){
$spr_cnt_tbl.find("td:nth-child(2)").not(':has(.label)').each(function(){
if( this.innerHTML===""){
$(this).wrapInner("<button class=btn btn-success id='sel_img' type='button'>Select Image</button>");
}
else {
$(this).wrapInner('<span class="label label-success"></span>');
}
});
};
});
});

Related

DataTables: Using AJAX, count how many rows in total have a specific value in a cell

My code is:
var table1 = $('#view-table').DataTable( {
fixedHeader: true,
"search": {
"smart": false
},
"columnDefs": [
{
"targets": [ 0,16 ],
"visible": false,
"bSearchable": true
},
{
"orderable": false,
"targets": [ 1,15 ]
}
],
"createdRow": function( row, data, dataIndex ) {
if ( data[16] == "yes" ) {
$(row).addClass('warning');
}
if ( data[0] == "yes" ) {
$(row).removeClass('warning');
$(row).addClass('success');
}
},
"ajax": '/getViewData',
"pageLength": 25
});
I have looked at jQuery How to count the no of rows in table by distinct column value but it only brings back what's on the screen at the time.
What I need is to see how many rows have the value of 'yes' in the 16th column for all the data that is brought back. Not just the data is on the screen. Everything.
All the examples I've tried, as the one above, only work where it's not AJAX based
I have the same problem a few weeks ago, I'm not sure if this is the best solution but it did the work then:
var count = table1.rows(function(idx, data, node) {
return data[16] == 'yes'
}).count();
EDIT: If you want that count after the ajax ends, you can user initComplete
initComplete: function(row, data, index) {
var count = table1.rows(function(idx, data, node) {
return data[16] == 'yes'
}).count();
console.log('count: ', count);
}, // initComplete()
EDIT 2: add jsfiddle
You should probably use ajax callback.
Instead of this "ajax": '/getViewData' do this:
"ajax": {
"type": "GET",
"url": "/getViewData",
"dataSrc": function(json){
//Count your rows here
return json.data;
}
}

Make edit link on datatable with multiple column values and global search on single/custom column(s)

How to create an edit link with function having multiple parameter from the data columns returned from ajax.
I read about the render callback but it only gets one column value & I need 2.
I need something like the following pseudo code.
"columnDefs": [ {
"targets": [0,1],
"data": "0,1",
"render": function ( data, type, full, meta ) {
return ``
}
} ]
As I'm disabling global search on all column except one. I cannot use the above code that use targets property. I don't know how to achieve this, please guide.
Edit: Complete code
var datatable = $('#datatable').DataTable({
"ajax": "/get_data/",
"processing": true,
"serverSide": true,
"deferRender": true,
"columnDefs": [
{ "searchable": false, "targets": [ 0,2,3,4,5,6,7,8,9,10,11 ] }
]
});
You can access row data using full variable, for example full[0] or full[1].
However instead of generating links in HTML, I would retrieve row data in a click handler as shown below:
$('#example').DataTable({
"columnDefs": [
{
"targets": [0, 1],
"render": function ( data, type, full, meta ) {
return 'Edit';
}
}
],
// ... other options ...
});
$('#example').on('click', '.btn-edit', function(){
// Get row data
var data = $('#example').DataTable().row($(this).closest('tr')).data();
edit(data[0], data[1]);
});
I needed Edit link on first column, so I followed #Gyrocode.com answer and it works great.
I also wanted to use the global search for searching but only on one column. Datatable ColumnDef Documentation gave me the clue so I ended up doing as follows.
Here The complete code:
var datatable = $('#datatable').DataTable({
"ajax": "/get_data/",
"processing": true,
"serverSide": true,
"deferRender": true,
"columnDefs": [
{
"targets": 0,
"render": function ( data, type, full, meta ) {
return 'Edit';
}
},
{ targets: 1, searchable: true },
{ targets: '_all', searchable: false }
]
});

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.

Why is rows() on a server-side DataTable not a function?

Why is rows() not a function on a server-side datatable?
The tables works fine beside that.
I have used rows() on five other client-side datatables before without any problems.
var tableComputerAndDevice = $('#tableComputerAndDevices').dataTable({
searching: true,
processing: true,
serverSide: true,
language: {
"processing": '<div style="background-color:#eee"> <span class="fa fa-spinner fa-pulse fa-5x"> </span> </div>'
},
ajax: {
url: url,
data: data,
type: "POST"
},
columns: [
{ "data": "checkbox", "searchable": false },
{ "data": "ComputerName", "searchable": true },
{ "data": "LastContact", "searchable": true }
]
});
var nodes = tableComputerAndDevice.rows('.selected').nodes();
console.log('nodes: ' + nodes);
Error: TypeError: tableComputerAndDevice.rows is not a function
Yes you judged it correctly. You need to change the dataTable to DataTable
Also to state that there is a difference between dataTable and DataTable.
The difference between the two is that the first will return a jQuery
object, while the second returns a DataTables API instance.
Change dataTable to DataTable. I answer my own question because I spent a hour with this bug, so I hope I can help others.
var tableComputerAndDevice = $('#tableComputerAndDevices').DataTable({

jQuery datatable - change cell value

I'm hoping someone can help me with this issue.
I am looking at a legacy application with the older version of datatables.net
It uses the function to populate the datatable and add colour to the row based on a returned name.
The code below works.
$(function () {
$("#ProfileTable").dataTable({
"bProcessing": true,
"bServerSide": true,
"bFilter": false, //Hide the search box
"bInfo": false,
"bPaginate": false,
"bLengthChange": false,
"sAjaxSource": 'DataTableHandler.ashx?dataTableId=ProfileTable',
"aoColumns": [ //aoColumns defines the properties of the table columns
{
"mDataProp": "Name",
"fnRender": function (o) {
return SetToolTip(o);
}
},
{
"mDataProp": "DollarValue",
"fnRender": function (o) {
return accounting.formatMoney(dollarValue);
}
,
"bUseRendered": false,
"sClass": "dataTableTextAlignRight"
}
],
"fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
//Highlight the row colors based on the Name. It must be identical to what is being retrieved from the database
var columnData = aData["Name"];
var div = document.createElement("div");
div.innerHTML = columnData;
if (div.innerText == "TOYS" {
$('td', nRow).css('background-color', '#E0E0E0');
}
if (div.innerText == "LOST TOYS" ) {
$('td', nRow).css('background-color', '#BDBDBD');
}
}
}
What i'm having trouble with is: If the Name = "LOST TOYS" and the DollarValue = 0 then change the DollarValue to display as an empty string (i.e. no value displayed in the cell).
I have looked at using fnUpdate but i can't get it to read the correct row and column. It comes back with "undefined".
Any suggestions are greatly appreciated.
thanks!
I had a brain fart.
The code goes to server side to get the data.
Here's the link to the information:Datatables forum posting about server side source

Categories