I want to add some class to row when I render a table, sample code:
$("#id").dataTable({
bProcessing: true,
sAjaxSource: com.mycompany.path.api.message[component],
aoColumns: [
{}, {},
{
sWidth: "37px",
fnRender: function(obj) {
return "<span>" + myData + "</span>";
}
}
]
});
In this example I could only control "td" tags, but I want to add some class for "tr" tag based on data that I get in fnRender() in cycle.
How I can do it with datatables?
Thanks,
Looks like in 1.7.3 available new functionality:
http://www.datatables.net/examples/advanced_init/row_callback.html
Related
I was unable to utilize the jQuery datatable plugin here:
https://editor.datatables.net/examples/inline-editing/simple
I kept getting an error, so I just dropped it and decided to do it myself.
Starting with the datatable:
$.ajax({
url: 'api/searchVoyageInfo.php',
type: 'POST',
data: '',
dataType: 'html',
success: function(data, textStatus, jqXHR){
var jsonObject = JSON.parse(data);
var table = $('#example1').DataTable({
"data": jsonObject,
"columns": [{
{ "data": "COLUMN1" },
{
"data": "COLUMN2",
"fnCreatedCell": function (nTd, sData, oData, iRow, iCol)
{
$(nTd).html("<a href='#' class='checkBound'>"+oData.COLUMN2+"</a>
<input type='text' class='editbound'
id='editbound' data-uid='"+oData.VOYID+"'
data-editbound='"+oData.COLUMN2+"' value='"+oData.BOUND+"
display: none;' />");
}
},
{ "data": "COLUMN3" },
// few more columns
}],
"iDisplayLength": 50,
"paging": true,
"bDestroy": true,
"autoWidth": true,
"dom": 'Bfrtip',
"buttons": [
// some extend buttons
]
});
},
error: function(// some stuff){
// do some other stuff
// this part is not important
}
});
Within COLUMN2, you should see a class 'checkBound' which is visible when the page loads. There is also an input class 'editbound' which is not visible.
Here is the function that is supposed to hide class 'checkBound' and then display class 'editbound':
$('#example1').on('click', 'tr > td > a.checkBound', function(e)
{
e.preventDefault();
var $dataTable = $('#example1').DataTable();
var tr = $(this).closest('tr');
var data = $dataTable.rows().data();
var rowData = data[tr.index()];
$('.checkBound').hide();
$('.editbound').show();
});
Using the above, when the page is finished loading, the datatable is displayed with no problem.
Upon clicking one of the cells with class 'checkBound' to display the input class 'editbound', the input does display itself, but it also displays every other cell in the column.
Before click:
After click:
As you can see, the first cell in the BOUND column is the cell that was clicked. But when clicked, the rest of the cells were activated. I want to prevent this from happening.
How can I make this work?
This is the way i created a column with a button in it . You should be able to do similar instead of button !
fields: [
{ name: "column_id", title:"View" ,itemTemplate: function(value) {
return $("<button>").text("buttontitle")
.on("click", function() {
//do something
return false;
});
}]
This is how I (somewhat) solved my problem. In the datatable section, I added an ID field called VOYID and included that ID with the class in the href and the input:
"data": "COLUMN2",
"fnCreatedCell": function (nTd, sData, oData, iRow, iCol)
{
$(nTd).html("<a href='#' class='checkBound"+oData.VOYID+"' id='checkBound'>"+oData.COLUMN2+"</a>
<input type='text' class='editbound"+oData.VOYID+"'
id='editbound' data-uid='"+oData.VOYID+"'
data-editbound='"+oData.COLUMN2+"' value='"+oData.BOUND+"
display: none;' />");
}
Then down in the button click section, I utilized the rowData to check for the exact class. This way, when you click the link, only the unique class will open and not all of the cells in the column:
$('#example1').on('click', 'tr > td > a.checkBound', function(e)
{
e.preventDefault();
var $dataTable = $('#example1').DataTable();
var tr = $(this).closest('tr');
var data = $dataTable.rows().data();
var rowData = data[tr.index()];
var voyid = rowData.VOYID;
$('.checkBound'+voyid).hide();
$('.editbound'+voyid).show();
});
Now, when I click on the link, it is only that cell that gets the input activated:
I am trying to add datatable info i.e "Page 1 of 1" between pagination text. Is it possible to achieve this?
var table = $('#example').DataTable({
pagingType: "full",
pageLength: 5,
info: true,
language: {
info: "Page _PAGE_ of _PAGES_",
paginate: {
previous: '<',
next: '>'
}
}
})
Add this to your code:
I edit my code to fit your case. Also it appears that datatable need to keep the original info element in order to do the update after you switch to another page, so you need to clone it to the new place instead of cut and paste, and set hide
drawCallback: function( settings ) {
$(".dataTables_paginate").children(':eq(1)').after($(".dataTables_info").hide().clone().css({'display':'inline-block', 'float': 'unset'}));
}
https://jsfiddle.net/96oy3buk/3/
so I'm trying to change the td class of my datatables elements dynamically. From my research i found fnRowCallback, it seems to be the solution but I can't get it to work. From 1 of the questions here at Stack I found:
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
for (var i in aData) {
// Check if a cell contains data in the following format:
// '[state] content'
if (aData[i].substring(0,1)=='[') {
// remove the state part from the content and use the given state as CSS class
var stateName= aData[i].substring(1,aData[i].indexOf(']'));
var content= aData[i].substring(aData[i].indexOf(']')+1);
$('td:eq('+i+')', nRow).html(content).addClass(stateName);
}
}
}
But this does not work for me, I get the error: Uncaught SyntaxError: Unexpected token, and my elements keep the "[class name] content" format. Here is my javascript function:
$('#tableId').DataTable({
"ajax" : "function.php",
"columns" : [
{
"data" : "id"
}, {
"data" : "firstElement"
}, {
"data" : "secondElement"
}, {
"data" : "thirdElement"
}],
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
for (var i in aData) {
// Check if a cell contains data in the following format:
// '[state] content'
if (aData[i].substring(0,1)=='[') {
// remove the state part from the content and use the given state as CSS class
var stateName= aData[i].substring(1,aData[i].indexOf(']'));
var content= aData[i].substring(aData[i].indexOf(']')+1);
$('td:eq('+i+')', nRow).html(content).addClass(stateName);
}
}
},
"iDisplayLength": 5,
"scrollX": true,
"orderFixed": [[ 0, "asc"]]
});
function.php gives me a JSON with all the fields, and in the ones I want the class altered I use "[class name] content" in the field. Any ideas on how to get it to work?
Thanks
Problem with your code is that aData would be an associative array, for example:
{ "id": 1, "firstElement": "[class] content" }
When you enumerate properties with for...in construct, i would hold property name (id, firstElement) and not numerical index.
Therefore you cannot use i to access cell within given row.
Another problem with your code is that it sets HTML content after it has been created. jQuery DataTables will be unaware that you've updated cell content.
I was able to successfully implement Datatables using the jQuery library. The problem is that when i click on page 2 in the pagination area it acts fine however when I go back to page 1 the records i selected are no longer selected.
Here is what it's supposed to do: datatables select row example
I updated my datatables to version: 1.10.15
Here is my call to handle the click event:
$("#datatable_users tbody").on("click","tr",function(){$(this).toggleClass("selected");});
Here is my code for creating the DataTable:
$("#datatable_'.$ref.'").dataTable({
"iDisplayLength": '.$itemlimit.',
"language": {
"url": "http://cdn.datatables.net/plug-ins/1.10.12/i18n/English.json"
},
"processing": true,
"serverSide": true,
"ajax": { // define ajax settings
"url": \''.Pluto::registry('web_base_uri').'service/datatable?req=1&ref='.$ref.'\',
"data": function(data) {
var datafilter= $("form#JqueryDataTableFormFilter_'.$ref.'").serializeControls();
$.each(datafilter, function(key, value) {
data[key] = value;
});
//console.log(datafilter);
}
},
"orderCellsTop": true,
"dom": "Bfrtip",
buttons: [
{
"text": "'.$search_label.'",
"className":"btn btn-default BtnjQueryDataTableFilter",
"action": function ( e, dt, node, config ) {
dt.ajax.reload();
}
}
]
});
As in server side processing the DataTable gets redrawn when you paginate so you need to keep track of what all was selected before clicking the next page and manually highlight the selected rows after each page click.
Here's an exact same working example featured on their website.
https://datatables.net/examples/server_side/select_rows.html
Let me know if you have any questions.
I'm using DataTables (datatables.net) to display data from an Ajax source and having trouble customizing it. One thing I would like to do is add a column so I can have for example an 'edit' button for each row.
The closest thing to that in the examples is here but I can't get that to work with an ajax source.
Currently, I'm using the following code to display my table:
fnServerObjectToArray = function ( aElements ){
return function ( sSource, aoData, fnCallback ) {
$.ajax( {
"dataType": 'json',
"type": "POST",
"url": sSource,
"data": aoData,
"success": function (json) {
var a = [];
for ( var i=0, iLen=json.aaData.length ; i<iLen ; i++ ) {
var inner = [];
for ( var j=0, jLen=aElements.length ; j<jLen ; j++ ) {
inner.push( json.aaData[i][aElements[j]] );
}
a.push( inner );
}
json.aaData = a;
fnCallback(json);
}
} );
}
}
$(document).ready(function() {
$('#example').dataTable( {
"bProcessing": true,
"sAjaxSource": 'get_data.php',
"fnServerData": fnServerObjectToArray( [ 'username', 'email' ] )
} );
});
Why don't you use fnRenderFunction in the aoColumns? As an example:
aoColumns: [ { "bVisible": false} , null, null, null, null,
{ "sName": "ID",
"bSearchable": false,
"bSortable": false,
"fnRender": function (oObj) {
return "<a href='EditData.php?id=" + oObj.aData[0] + "'>Edit</a>";
}
}
]
You can use it to format the value from the server side.
See similar example on the http://jquery-datatables-editable.googlecode.com/svn/trunk/ajax-inlinebuttons.html (ignore specific settings for the editable plugin)
I've created columns with edit button and links and so on, but usually i do everything server side by custominzg the data i return and then show/hide them with the aoColumns option. I don't really understand what you are tring to achieve: display server side data as a link?
Had the same problem a few months back. This is what I did.
By no means an elegant slution, but this worked.
As you might already know, DataTables do have an overload to accept Javascript Arrays.
So I made by $.ajax call. got my json, parsed it to a javascript array and then while parsing I created an extra element (an anchor tag) with href="edit.php?email=passed_email" Then on the column headers and added a column called Edit. Those values were fed to "aaData" and "aoColumns". And then the table was populated.
And BTW, if you looking for inline editing, check the following link.
DataTables editing example - with jEditableplugin
i have some RND on this problem and get this hope this will help you out.