Custom rendering when using server side processing - javascript

I was wondering if the rendering of the table after receiving an ajax response can be modified. This seems related to the render function described here: https://www.datatables.net/manual/orthogonal-data.
My server returns Data like
{
"name":
{
id: "123456",
value: "Tiger Nixon"
}
}
I want to add to each name cell the id of the name as data-attribute or as id for the td and want to add a .on( "click", handler ) for each cell.
Is this possible?
Thanks in advance

You can use DT_RowData or DT_RowAttr (requires DataTables 1.10.5 or higher) parameters in your returned data to assign attributes to <tr> element which you can later retrieve in click handler, see Server-side processing chapter in the manual.
Alternatively you can use render method but it may not be as effective. I assumed below that index of your name column is 0 and that you want to set data-id attribute.
var table = $('#example').DataTable({
"columnDefs": [{
"data": "name.value",
"targets": 0,
"render": function ( data, type, full, meta ) {
if(type === 'display'){
$('#example').DataTable().cell(meta.row, meta.col).nodes().to$().attr('data-id', full['name']['id']);
}
return data;
}
}]
});
You can add click event handler using the code below:
$(document).ready(function(){
var table = $('#example').DataTable({
// Define DataTables initialization options here
});
$('#example tbody').on('click', 'td', function(){
// Use table to access various API function
//
// For example:
// var data_cell = table.cell(this).data();
});
});

This is possible by using the columns.createdCell function.
The answer of Gyrocode is correct for an old DataTables version.

Related

Datatables has only 10 rows accessible outside the DataTables creation function

I am using Django and in one of my tamplates I use datatables (1.10.19) to display my table data.
This is how my code looks like:
$(document).ready( function () {
table = $('#mytable').DataTable({
"pagingType": "full_numbers",
data: dataSet,
columns: [
{ title: "Naslov zahtjeva" },
{ title: "Datum slanja" },
{ title: "Status" },
{ title: "Rok Izvršenja." },
{ title: "Id zahtjeva" },
],
"fnCreatedRow": function(row, data, index){
$(row).addClass("clickable-row");
$(row).attr('data-href', data[4]);
$(row).addClass("table_row_point");
},
});
Problem occurs at the line -> $(row).attr('data-href', data[4]);
I have a different function that is suposed to use that 'ID' from 'data-href' attribute in order to go to another page like this
jQuery(document).ready(function($) {
$(".clickable-row").click(function() {
window.location = $(this).data("href");
});
});
Thing is it works fine for first 10 rows, and when I try 'console.log( this );' I get
Only for the first 10 rows, and it acts like other 3000 don't even exist, I believe it is connected to the default value of 10 rows that appear, but it makes no sense to me for data to be displayed normally, but the 'tr' element not to exist for all, but 10 of them.
Note: When I place this function into DataTable creation code (1st snippet) it shows all the tr elements
$('#mytable tbody').on( 'click', 'tr', function () {
console.log( this );
} );
If someone has any idea it would be much appreciated
fnCreatedRow function is executed everytime datatable creates the <tr> element in the dom. Since you have enabled pagination, function is run only on the <tr> elements created at the time. If you move on to next page, you'll see that console prints next set of rows.
By the way I think createdRow is preferred over old fnCreatedRow naming convention. https://datatables.net/reference/option/createdRow

Datatable update from another component

I'm using the datatables table plugin for jquery. I have another component that uses Ajax to retrieve an object from the server. I'd like to update the database with this object. I'm struggling on how to piece this together. The Ajax returns an object that is in the format that the datatable will accept for data. But how can I update the datatable from another components Ajax call? I'm using python flask and jinja2 templating. Here is the javascript as it currently exist:
$(function() {
var container = document.getElementById('visualization');
var items = new vis.DataSet({{documents|safe}});
var options = {};
var timeline = new vis.Timeline(container, items, options);
timeline.on('select', function (properties) {
$.getJSON('/getDependencyHistory', {
uuid: properties.items[0]
}, function(data) {
console.log("Place this into the datatable");
});
return false;
});
});
$(document).ready(function() {
var table = $('#example').DataTable();
});
here is a really simple one that "fools" the ajax call.
go to http://live.datatables.net/nesadivo/1/edit
Click on Run With JS button to initialize everything. Click on the go button to go get the data
$(document).ready(function() {
// created a global variable for the datatable to us to find the data
var dtData = null;
// On the button click, use regular ajax to get the data
$("#btnGo").on("click", function(){
$.ajax({url:"http://live.datatables.net/examples/server_side/scripts/server_processing.php",
success:function(cData){
// on success, set the global variable then reload table
dtData = JSON.parse(cData);
$('#example').DataTable( ).ajax.reload();
},
error:function(err){debugger;}} );
});
// initialize the table on page load
$('#example').DataTable( {
"ajax": function(a,callback,c){
callback(dtData);
}
});
});

How to update/add buttons once instantiated datatables

I am new to JavaScript and I lack knowledge javascript objects.
I would like to know how I can add the extension of the datatable 1.10 button once created .
My code is:
var table;
$('#MyDiv').DataTable({someCode;});
$.fn.dataTable.ext.buttons.ok = {
text: 'OK',
action: function (e, dt, node, config) {
console.log("Hi");
}
};
table = $('#MyDiv').DataTable();
//!Here I want to add my button in table var!
Option 1
The easiest way to do it (in my opinion) is to use the option form of the button declaration, instead of the function form you are attempting to use here. In your case, that would look something like this:
table = $('#MyDiv').DataTable({
/*Other DataTables config options go here*/
buttons: [
{
text: 'OK',
action: function ( e, dt, node, config ) {
console.log("Hi");
}
}
]
});
This can be found in the DataTables examples, which is a great source for DataTables information.
Option 2
If instead you wish to keep using the function notation, then you would simply have to add a button declaration to the options instead of the whole action/text block that is there in the above example. See below:
var table;
//You should not have 2 .DataTable() calls, so I removed this one
//Move any other options you had to the other call below
$.fn.dataTable.ext.buttons.ok = {
text: 'OK',
action: function (e, dt, node, config) {
console.log("Hi");
}
};
table = $('#MyDiv').DataTable({
/*Other DataTables config options go here*/
buttons: [
'ok'
]
});
Either way should work, it just depends on how you prefer to organize your code.
I'd also refer you to the custom buttons documentation on the DataTables website to get more information or to see where I got these code blocks from.

Delete rows in Datatable before destroying

I am initializing a Datatable each time the function lds is called. The function lds pulls data for table and appends the relevant HTML by
$('#tablebody').html(data);
After that I am initializing a datatable like so,
$('#rTable').Datatable({
paging:false,
destroy: true
});
This solves the problem of the error "Datatables cannot be initialized" if I call the lds function again. But the old rows are retained that were appended previously. I have tried the following approaches:
Assigned var table to the initialization of Datatable and put table.empty() at the beginning of lds. But as expected, the table variable is undefined.
Tried to delete row(0) while length > 0 but that messes the table and deletes the as well.
Tried ('#rTable').empty() but due to this Datatables throws an error d[i] not defined.
What is an approach I can take to empty the rows each time the function lds is called.
Destroy an existing table on a button click
var table = $('#myTable').DataTable();
$('#tableDestroy').on( 'click', function () {
table.destroy();
} );
Reload a full table description from the server, including columns:
var table = $('#myTable').DataTable();
$('#submit').on( 'click', function () {
$.getJSON( 'newTable', null, function ( json ) {
table.destroy();
$('#myTable').empty(); // empty in case the columns change
table = $('#myTable').DataTable( {
columns: json.columns,
data: json.rows
} );
} );
} );

Sorting Tablesorter columns by input value

I am using jQuery Tabelsorter and it's working great.
But I want inside every -field an input-tag where the value for the sorting-script is located inside the input value param.
NOW: <td><?php echo $value; ?></td>
GOAL: <td><input value="<?php echo $value; ?>"></td>
How can I tell jQuery Tablesorter the new "value" location?
Found at Tablesorter 2.0 Samples http://tablesorter.com/docs/example-option-text-extraction.html
Example:
textExtraction: function(node) {
// extract data from markup and return it
return node.childNodes[0].childNodes[0].innerHTML;
}
My try but not working:
textExtraction: function(node) {
// extract data from markup and return it
return node.childNodes[0].val();
}
Instead of table sorter use kendoui.its provide more features & easy to use
kendoui
Tthe original tablesorter plugin has an issue using the updateCell method, so this method will not work when updating input values. But you can try my fork of tablesorter which doesn't have this issue.
Here is a demo of the all of the code below put together.
Basically instead of using textExtraction which applies to ALL table cells, you just need to add a parser:
$.tablesorter.addParser({
id: "inputs",
is: function () {
return false;
},
format: function (s, table, cell) {
return $(cell).find('input').val() || s;
},
type: "text"
});
then tell tablesorter which column to apply it to (zero-based index):
$('table').tablesorter({
headers: {
0: { sorter: "inputs" } // zero-based index (first column = column 0)
}
});
Then make sure any changes to the inputs (unless you make them read-only) are recognized by tablesorter and sent to your server
var resort = true, // resort table after update
// update all input types within the tablesorter cache when the change event fires.
// This method only works with jQuery 1.7+
// you can change it to use delegate (v1.4.3+) or live (v1.3+) as desired
// if this code interferes somehow, target the specific table $('#mytable'),
// instead of $('table')
$(window).load(function () {
// this flag prevents the updateCell event from being spammed
// it happens when you modify input text and hit enter
var alreadyUpdating = false;
$('table').find('tbody').on('change', 'input', function (e) {
if (!alreadyUpdating) {
var $tar = $(e.target),
$table = $tar.closest('table');
alreadyUpdating = true;
$table.trigger('updateCell', [ $tar.closest('td'), resort ]);
// *** update your server here ***
setTimeout(function () {
alreadyUpdating = false;
}, 10);
}
});
});

Categories

Resources