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.
Related
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 }
]
});
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>');
}
});
};
});
});
I am aware that thanks to fnReloadAjax or combination of fnClearTable() and fnAddData() I can reload some fresh data
but is it possible this way somehow to redefine settings of table, in particulary: columns names, which are hidden, which are visible?
UPDATE:
If you will decide for destroying the table the easier way as checking existence and destroying like this:
if $.fn.DataTable.isDataTable("#element") {
$('#element').DataTable().destroy();
}
can be just setting the property in DataTable definition: bDestroy: true
I think you can redfine the settings by destroying the dataTable altogether like:
//part1
$( "#element" ).dataTable({
"sPaginationType": "full_numbers",
"iDisplayLength": 25,
"aoColumnDefs": [
{ "bSortable": false, "aTargets": [ 0 ] } //cannot sort using column 1
]
});
----------
//part2
$( "#element" ).dataTable().fnDestroy();
$('#element').dataTable( {
"aoColumnDefs": [
{ "bVisible": false, "aTargets": [2] } //hiding the column 3
]
} );
Here I just destroyed the dataTable for no reason but you can link it with some event.
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
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");
}
});