I'm looking on the datatables.net website for some clarification or documentation rather about what to do if you have more than 1 table on a single page and want to handle each one differently.
I tried the obvious. Assigning each to a different id and then performing the code for each in my js but for some reason its not allowing it. I'm not getting an error but datatables itself breaks and doesn't perform anything.
$(document).ready(function() {
var oTable = $('#inbox').dataTable( {
"bAutoWidth": false,
"aoColumnDefs": [
{ "bSortable": false, "aTargets": [ 0, -1 ] },
{ "sWidth": "20px", "aTargets": [ 0, -1 ] },
{ "sWidth": "100px", "aTargets": [ 1 ] },
{ "sWidth": "150px", "aTargets": [ 3 ] }
]
} );
var oTable = $('#sent').dataTable( {
"bAutoWidth": false,
"aoColumnDefs": [
{ "bSortable": false, "aTargets": [ 0, -1 ] },
{ "sWidth": "20px", "aTargets": [ 0, -1 ] },
{ "sWidth": "100px", "aTargets": [ 1 ] },
{ "sWidth": "150px", "aTargets": [ 3 ] }
]
} );
});
UPDATE
http://pastebin.com/4d3kPmk0
$(document).ready(function() {
var oTable = $('.dataTable').dataTable( {
"bAutoWidth": false,
"aoColumnDefs": [
{ "bSortable": false, "aTargets": [ 0, -1 ] },
{ "sWidth": "20px", "aTargets": [ 0, -1 ] },
{ "sWidth": "100px", "aTargets": [ 1 ] },
{ "sWidth": "150px", "aTargets": [ 3 ] }
]
} );
});
$(window).load(function(){
/*
* Tabs
*/
$('#tab-panel-1').createTabs();
});
You are redeclaring the same variable.
var oTable = $('#inbox').dataTable({ /* ... */ });
var oTable = $('#sent').dataTable({ /* ... */ });
The "oTable" part of this is just what Allan (the author) happens to use in his examples to fit in with his conventions. The lowercase 'o' refers to something that's an object, and it's a table. But you can use whatever name you want.
You had the right idea, but you need to use:
var inboxTable = $('#inbox').dataTable({ /* ... */ });
var sentTable = $('#sent').dataTable({ /* ... */ });
And then if you're following his other examples on the site, you just substitute your own variable name for "oTable".
Live sample: http://live.datatables.net/amixis/edit#javascript,html
[update]
I should mention that recently I'm storing multiple tables in a nested object; I have a polling mechanism that iterates over particular arrays of tables (and not others), so the sample object looks something like this:
var oTables = {
"polling" : [
$('#someTable').dataTable(opts),
$('#anotherTable').dataTable(opts)
],
"nonpolling" : [
$('#staticTable').dataTable(opts)
]
};
The net result is still the same. But I can now call setTimeouts over my array of polling table objects:
if(someBoolean) {
for(var i=0; i < oTables.polling.length; i++) {
setTimeout(pollingFunction, 5000)
}
}
(highly simplified)
Related
I have created a query table using data from json.
I am trying to combine two column values in one
but i always get undefined data when i try to combine two columns.
I am not sure what is wrong here.
not sure what is wrong here
$("#submit").click(function(){
var dataTableExample = $('#tbl_jad').DataTable();
$('#tbl_jad').show();
if (dataTableExample != 'undefined') {
dataTableExample.destroy();
}
dataTableExample =
$('#tbl_jad').DataTable({
"aaData": data.d.results,
"aoColumns": [
{
"mData": "ID"
},
{
"mData": "Position_x0020_Number",
},
{
"mData": "Title"
}, {
"mData": "Type_x0020_of_x0020_Action"
}, {
"mData": "Series"
}]
,
"columnDefs": [
{
"render": function ( data, type, row ) {
return data +' ('+ row[0]+')';
},
"targets": 1
},
{ "visible": false, "targets": [ 0 ] }
]
});
}
});
return data +' ('+ row["ID"]+')'
where ID is the column heading or column name
I thought to be a simple thing, but!
Using DataTables, I would like to have the first column of the table hidden and use that cell data in an HTML image link in the next column cell.
html link using "User_ID", http://somepage.php?UID=data0
I have looked at fnGetData() and mRender and I just confused now.
MY CODE:
"aoColumns": [
{ "mData": "User_ID",
"bVisible": false, "bSearchable": false, "bSortable": false
},
{ "mData": null,
"bSearchable": false, "bSortable": false,
"sClass": "center",
"sDefaultContent": '<img src="images/look.png" width="16">'
},
I always help myself with this trick:
Don't set bVisible to false cause you will not have the data in the row. It's not rendered at all. Use sClass and set display:none. This way the column is invisible to the user, but it is still there.
Then you can use mRender to show a custom cell template:
"aoColumnDefs": [{
"aTargets": [0],
"sClass": "hiddenID"
}, {
"aTargets": [1],
"bSearchable": false,
"bSortable": false,
"sClass": "center",
"mRender": function(data, type, full) {
return 'Click me';
}
}, {
"aTargets": [2],
}, ]
Now the data is there, sortable and filterable.
Look at this Plunker and style.css to understand the concept behind this hack.
You may have a closer look at mData so you can do a callback function and dont have to use the hidden column:
// Using mData as a function to provide different information for
// sorting, filtering and display.
$(document).ready( function() {
var oTable = $('#example').dataTable( {
"aoColumns": [
{ "mData": "User_ID",
"bVisible": true, "bSearchable": false, "bSortable": false
}
],
"aoColumnDefs": [ {
"aTargets": [ 0 ],
"mData": function ( source, type, val ) {
if (type === 'set') {
source.id = val;
// Store the computed dislay and filter values for efficiency
source.id_display = val=="" ? "" : '<img src="images/look.png" width="16">';
source.id_filter = val=="" ? "" : val;
return;
}
else if (type === 'display') {
return source.id_display;
}
else if (type === 'filter') {
return source.id_filter;
}
// 'sort', 'type' and undefined all just use the integer
return source.id;
}
} ]
} );
} );
I have datatable with id, firstName, lastName, phone, updated fields.
Problem: I add to datatable only four fields (id, firstName, lastName and phone). Updated field is hidden.
Question: how to sort datatable by updated field?
My code:
$('#table').dataTable({
sDom: '<"top"fi>tS',
sScrollY: ($(window).height() - 250) + "px",
bPaginate: false,
bDeferRender: true,
bAutoWidth: false,
oLanguage: {
sInfo: "Total: _TOTAL_ entities",
sEmptyTable: "No pending entities"
},
"aoColumnDefs": [
{ "iDataSort": 4, "aTargets": [ 0 ] }
],
"aoColumns": [
{ "sWidth": "10%" },
{ "sWidth": "40%" },
{ "sWidth": "30%" },
{ "sWidth": "20%" },
{ "sTitle": "updated ", "bVisible":false }
],
fnCreatedRow: function( nRow, aData, iDataIndex ) {
$(nRow).attr('id', aData[0]);
}
});
table.fnAddData([id, firstName, lastName, phone, updated]);
From the documentation:.
iDataSort The column index (starting from 0!) that you wish a sort to be performed upon when this column is selected for sorting. This can be used for sorting on hidden columns for example.
Default: -1 Use automatically calculated column index
Type: int
// Using aoColumnDefs
$(document).ready( function() {
$('#example').dataTable( {
"aoColumnDefs": [
{ "iDataSort": 1, "aTargets": [ 0 ] }
]
} );
} );
// Using aoColumns
$(document).ready( function() {
$('#example').dataTable( {
"aoColumns": [
{ "iDataSort": 1 },
null,
null,
null,
null
]
} );
} );
you can simply use { "iDataSort": 4 } here (4 is the index of your hidden field)
var data = [
["1","john","mathew","1234",[]],
["2","Mary","rose","1234","1"],
];
To add hidden fields and to add data to table
aaData: data,
aoColumns :[
{ "sTitle": "id","bSortable": false },
{ "sTitle": "firstName","bSortable": false, },
{ "sTitle": "lastName", "bSortable": false,},
{"sTitle": "phone","bSortable": false},
{"sTitle": "updated ", "bVisible":false },
]
To add hidden fields use "bVisible":false
I was facing a problem by sorting the hidden column in runtime, don't know the approach is valid or not. I used the following lines to hide the column via CSS
td:nth-of-type(2) {
display: none;
}
Where 2 is your column, assign a class to your <th class="mycolum1"> and use jquery to sort it like
$("#button").click(function(){
$(".mycolumn").click();
})
Pardon me if the approach is not valid but in my case it is 100% acceptable.
I am trying to quickly create a simple display of results from an internal API using DataTables. The API returns JSON in the following structure:
obj {
status: 1,
results: 100,
offset: 25,
limit: 25,
data: [
[1]: {
title: "Blah blah one",
description: "Doesn't really matter",
misc: "Yadda yadda"
},
[2]: {
title: "Blah blah two",
description: "Doesn't really matter",
misc: "Yadda yadda"
},
]
}
I can't/don't want to change the API structure just because DataTables uses a weird structure, but I would like to access the built in functionalities for paging, dynamic loading, etc. DataTables seems to allow for custom data objects, and I've gotten the table to load with the following:
$(document).ready(function() {
$('#example').dataTable( {
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "http://api.oursite.com/api?limit=100",
"fnServerData": function( sUrl, aoData, fnCallback, oSettings ) {
oSettings.jqXHR = $.ajax( {
"url": sUrl,
"data": aoData,
"success": fnCallback,
"dataType": "jsonp",
"cache": false
} );
},
"sAjaxDataProp": "data",
"aoColumns": [
{ "mData": "title" },
{ "mData": "description" },
{ "mData": "misc" },
]
} );
});
But, none of the paging or sorting functions work. I think this is because DataTables requires a results count and paging variable in the object— "iTotalRecords" and "iTotalDisplayRecords". Is this correct? Is there any way to use the api variables instead? Thanks in advance. I'm currently not getting any errors in the dev console, so if it's erroring it's doing so silently...
While initializing the datatable, instead of directly assigning source to Ajaxsource, you can set the aaData to the javascript function where you can manipulate to return only obj.data. You need handle few things manually.
$('#tblExample').dataTable({
"bJqueryUI": true,
"bDestroy":true,
"bSortable": false,
"sAjaxSource": "",
"aaData":GetData(),
"aoColumns": [
{
"sTitle":"Index","mDataProp": null, "sWidth": "20px", "sDefaultContent": "<span class='ui-icon ui-icon-circle-close' onclick='RemoveActiveItem(this);'></span>", "bSortable": false},
{ "mDataProp": "Year"},
{ "mDataProp": "Month"},
{ "mDataProp": "Savings"}
]
});
This question is regarding the plugin found here: http://www.datatables.net/usage/columns
var hidecols = '{"sClass": "Hide", "aTargets": [0]},{"sClass": "asdf", "aTargets": [1]},{"sClass": "qwer", "aTargets": [2]}';
var hidecolsobj = eval('(' + hidecols + ')');
var oTable = $('#MainContent_OverviewTable').dataTable({
"sPaginationType": "full_numbers",
"bProcessing": true,
"bServerSide": true,
"aoColumnDefs":
[
hidecolsobj, // <--------- *** HERE ***
],
"sAjaxSource": "Services/Service.svc/GetDataTableOutputOverview",
"fnServerData": function (sSource, aoData, fnCallback) {
var jsonAOData = JSON.stringify(aoData);
$.ajax({
type: "POST",
async: true,
url: sSource,
contentType: "application/json; charset=utf-8",
data: '{"Input":' + jsonAOData + '}',
dataType: "json",
success: function (msg) {
fnCallback(msg);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.responseText);
}
});
}
});
So the code works fine with no errors but the class "qwer" is the only one that is being applied to my table. I tested this out and it only applies the class that appears last in my list of objects. I would like each of the columns to have the classes defined in the hidecols variable. How can I do that?
This is how it appears in the documentation from the Datatables website:
$('#example').dataTable( {
"aoColumnDefs": [
{ "sClass": "my_class", "aTargets": [ 0 ] }
]
} );
EDIT:
"aoColumnDefs":
[
{ "sClass": "Hide", "aTargets": [0] },
{ "sClass": "asdf", "aTargets": [1] },
{ "sClass": "qwer", "aTargets": [2] }
],
The above edit works properly but this isn't an option for me. I need to be able to build the string hidecols dynamically.
You are passing DataTables a string for the aoColumnDefs parameter. Just remove the quote marks around the hidecols "string" to make it an array of objects. That will remove the need for the evil (eval).
var hidecols = [{"sClass": "Hide", "aTargets": [0]},{"sClass": "asdf", "aTargets": [1]},{"sClass": "qwer", "aTargets": [2]}];
Allan
Ah! I figured out how to do it!
Instead of doing this:
"aoColumnDefs":
[
hidecolsobj, // <--------- *** HERE ***
],
I should be doing this:
var hidecols = '[{"sClass": "Hide", "aTargets": [0]},{"sClass": "asdf", "aTargets": [1]},{"sClass": "qwer", "aTargets": [2]}]';
var hidecolsobj = eval('(' + hidecols + ')');
"aoColumnDefs": hidecolsobj, // <--------- *** HERE ***