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
Related
I would like to add a context menu to each of my DataTable rows.
I want to get the row that was clicked on and then some way to identify it (I suppose the first cell value which contains the primary key would work) and then send an AJAX request containing the PK and option clicked.
I have figured out how to get the row by using "tr" as a selector, but how can I get the 1st cell's value (which contains the primary key). This prints out all of the cells:
$(function(){
$.contextMenu({
selector: 'td',
trigger: 'right',
callback: function(key, options) {
var m = $(options.$trigger).text();
window.console && console.log(m) || alert(m);
},
items: {
"delete": {name: "Delete", icon: "delete"},
});
});
Also, is this the best way to do this? I plan to have ~10 options in the context menu that interact with the rows. I am using Django as the backend.
Always use the API when you want to interact with DT. If you have an instance
var table = $('#example').DataTable( {..} )
then retrieve the current row by passing options.$trigger which holds the <tr> node :
$.contextMenu({
selector: 'tr',
trigger: 'right',
callback: function(key, options) {
var row = table.row(options.$trigger)
switch (key) {
case 'delete' :
row.remove().draw()
break;
case ...
}
},
items: {
'delete': { name: 'Delete', icon: 'delete' },
...
}
})
but how can I get the 1st cell's value (which contains the primary
key).
row.data()[0]
demo -> http://jsfiddle.net/z2q5scgr/
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.
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
} );
} );
} );
I am using TableTools and DataTables v1.10 in same page.
My main page has table and empty div for modal.
<div id="resultDiv">
<table id="mainTable"> ... </table>
<div id="detailModal">
<div id="detailModal-content"></div>
</div>
</div>
<script>
$(document).ready(function () {
var mainTable = $('#mainTable').DataTable({
"dom": 'T<"clear">lrtip',
"tableTools": { ... },
"columns": [
{
"data": null,
"render": function(data, type, row, meta) {
return 'Details';
}
},
....
],
........
});
});
function loadDetail(id) {
$.ajax({
async: false,
url: ...,
success: function(respose) {
var tableInstance = TableTools.fnGetInstance('detailTable');
console.log(tableInstance); //null
}
});
}
</script>
Separate detail page has another table which get rendered in detailModal-content div.
<table id="detailTable">
</table>
<script>
$(document).ready(function () {
var mainDetailTable = $jq11('#detailTable').DataTable({
"dom": 'T<"clear">ltipr',
"tableTools": { ... },
..............
});
});
</script>
Here first TableTools of mainTable is working fine but for second table it is not working (I can click button but clicking on it doesn't create xls file). I am trying to solve this by calling fnResizeButtons() after table created as suggested here. But tableInstance is null.
Any suggestion?
From what I can tell you're having problems with TableTools (not the DataTable) not working on the table which is in the modal?
I've had similar issues myself and it's down to the table being initialised when it's invisible and something to do with the Flash, it can be fixed and this is what I used to fix a similar issue with tables on different bootstrap tabs not having functional TableTools except on the table which was initially visible:
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
var target_id = $(e.target).attr("href");
var jqTable = $(target_id).find("table");
var oTableTools = TableTools.fnGetInstance( jqTable[0] );
if (oTableTools != null && oTableTools.fnResizeRequired()){
/* A resize of TableTools' buttons and DataTables' columns is only required on the
* first visible draw of the table
*/
jqTable.dataTable().fnAdjustColumnSizing();
oTableTools.fnResizeButtons();
}
});
Of course, you'll have to grab the table instance on the shown.bs.modal or whatever other event shows your modal but that should fix the TableTools issue.
Hope that helps.
Your function loadDetail() doesn't load response into <div id="detailModal-content"></div>, therefore second table doesn't get initialized.
Corrected loadDetail() function should look something like:
function loadDetail(id) {
$.ajax({
async: false,
url: '/script.php',
data: { 'id' : id },
success: function(response){
$('#detailModal-content').html(response);
}
});
}
watch out if you're table header is already a table,
then use jqTable[1] or even better jqTable.get(1)
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.