So I'm looking at this example and am trying to make it work for me.
I want to add the select options to my table when I use server side processing. Since I have only used version 1.10 I always get confused when I see this old API.
I don't understand how I can use this function in 1.10:
"sAjaxSource": "../examples_support/server_processing.php",
"fnServerData": function ( sSource, aoData, fnCallback ) {
/* ... additional variables ... */
$.getJSON( sSource, aoData, function (json) {
/* Create the select elements on the first run */
if ( json.sEcho == 1 )
{
$("tfoot th").each( function (i) {
/* Insert the select menu */
this.innerHTML = fnCreateSelect(json.select[i]);
/* Add the event listener for the newly created element */
$('select', this).change( function () {
oTable.fnFilter( $(this).val(), i );
} );
} );
}
/* DataTables callback */
fnCallback(json)
} );
}
The converting guide just lists fnServerData as ajax.
This is my initialization code:
$('#dataTables-outputTest').DataTable({
"processing": true,
"serverSide": true,
"ajax": "/TestData/data-source",
"columns": [
{ "data": "thing1",
"searchable": true},
{ "data": "thing2",
"searchable": true},
...
{ "data": "link",
"searchable": false,
"orderable": false},
],
"initComplete": function () {
this.api().columns().every( function () {
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo( $(column.footer()).empty() )
.on( 'change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search( val ? '^'+val+'$' : '', true, false )
.draw();
} );
column.data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' )
} );
} );
}
});
How do I use that function and how do I have to rewrite it to work for me?
It seems I didn't understand what fnServerData did. It can be used to send additional data to the server from the client. So it's the oposite of what I'm trying to do.
I managed to do this by using this code:
"processing": true,
"serverSide": true,
ajax: {
url: '/MyApp/data-source',
data: function ( data ) {
data.someKey = "someValue";
},
},
Then when I print my request on the server I find a new object in the dictionary:
'someKey': ['someValue']
Related
I am using DataTables select input and I am capturing only the first three columns. Right now, I would like to add a text on the top of the select inputs. Is there a way to add a text on DataTables. For example select product on DataTables select inputs
I am using DataTables. Here is my select inputs my looks like now:
Here is a visual look of how I would like it to be -- just adding a text like this that says select something.
Here is my code:
<script>
$(document).ready(function() {
$(".se-pre-con").fadeOut("slow");
$('table').DataTable( {
fixedHeader: true,
"ordering": false,
columnDefs: [{
targets: 7,
createdCell: function(td, cellData) {
$(td).hover(function(){
if (cellData === ''){
$(this).css('cursor','pointer').attr('title', 'Some text');
}
})
}
}],
language: {
processing: "Bitte warten ..",
search: "Suchen",
lengthMenu: "_MENU_ Einträge anzeigen",
info: "_START_ bis _END_ von _TOTAL_ Einträgen",
infoEmpty: "Keine Daten vorhanden",
infoFiltered: "(gefiltert von _MAX_ Einträgen)",
infoPostFix: "",
loadingRecords: "Wird geladen ..",
zeroRecords: "Keine Einträge vorhanden",
paginate: {
first: "Erste",
previous: "Zurück",
next: "Nächste",
last: "Letzte"}
},
initComplete: function () {
this.api().columns().every( function () {
var column = this;
if (column.index() <3 ) {
var select = $('<select><option value=""></option></select>')
.appendTo( $(column.header()).empty() )
.on( 'change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search( val ? '^'+val+'$' : '', true, false )
.draw();
} );
column.data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' )
} );
}
});
}
} );
} );
</script>
Inside the initComplete function change this
var select = $('<select><option value=""></option></select>')
to
var select = $('<select><option value="">Select a Platform</option></select>')
It works, if you need different placeholder for every select change it as per the need.
Something like this: https://codepen.io/piyush_05/pen/JjGbwZY
I'm using an 'Individual column searching' as specified in DataTables' documentation.
What I want to accomplished is to make the second search field (located below the column) value UPPERCASE as the user types a date.
Here's my .js file:
$(document).ready(function() {
// Setup - add a text input to each footer cell
$('#example tfoot th').each( function () {
var title = $(this).text();
$(this).html( '<input type="text" placeholder="Search '+title+'" />' );
} );
// DataTable
var table = $('#example').DataTable({
/*More Code*/
columnDefs: [
{ targets: 0, visible: false },
{ targets: 1, render: $.fn.dataTable.render.moment( 'D-MMM-YY' ) }
],
columns: [
{ /* DATA */},
{ data: "logEntryTime" },
{ /* DATA */},
{ /* DATA */},
{ /* DATA */},
{ /* DATA */},
]
/*More Code*/
});
// Apply the search
table.columns().every( function () {
var that = this;
$( 'input', this.footer() ).on( 'keyup change', function () {
if ( that.search() !== this.value ) {
that
.search( this.value )
.draw();
}
} );
} );
} );
Any ideas?
One simple way to do this is to use css.
text-transform: uppercase;
However, that only changes the appearance of the text. If you need to change the value of the text, then you would use some JS.
input.value.toUpperCase()
I have a function that creates an instance of DataTables and for some reason it initializes n-times after destruction. I only noticed this because I add custom fields on init and they were multiplying. I could prevent that but that only deals with the symptom.
To clarify, after I "destroy: the instance and reinitialize it, to change the data source, if it's the second time it initializes twice. Three times if it's the 3rd time, etc.
I speculate that the table variable is part of the closure formed by the function because even if I set table = null the same thing happens.
How can I prevent this?
DataTables Function
/*Create a DataTable on tableElementID using pageUrl as the source*/
function ajaxLoadTable ( pageUrl, tableElementID ) {
window.table = $(tableElementID)
.on( 'init.dt', function () {
//The success function is used internally so it should NOT be overwritten, have to listen for this event instead
//Add our custom fields _length refers to an element generated datatables
if ( additionalElements.saveButton ) {
$(tableElementID + '_length').after('<div class="dataTables_filter"><button>Save All Edits</button></div>');
}
if ( additionalElements.selectState ) {
$(tableElementID + '_length').after('<div class="dataTables_filter"><label>Project State: <select name="projectState" style="width:auto;"><option>Select ...</option><option value="Active">Active</option><option value="Historical">Historical</option></select></label></div>');
}
if ( additionalElements.searchBox ) {
$(tableElementID + '_length').after('<div class="dataTables_filter"><label>Search:<input type="search" id="customSearch" style="width:auto;"></label></div>');
}
})
.DataTable({
"processing": true,
"serverSide": true,
"ajax":{
type: "POST",
url: pageUrl,
data: function ( additionalData ) {
$('.serverData').each( function( index, element ){
if( element.nodeName === "SELECT"){
additionalData[element.name.toUpperCase()] = element.options[element.selectedIndex].value;
return true; //return true is equivalent to continue for $.each
}
additionalData[element.name.toUpperCase()] = element.value;
});
},
dataType: "json"
},
"pageLength": 4,
"lengthMenu": [ 4, 8, 12, 16, 24 ],
"searchDelay": 1500,
"columnDefs":
{ "targets": 0,
"orderable": false,
"data": {
"_": "display"
}
}
});
}
Destruction Function
/*Load the selected project state*/
$('html').on( 'change' , '[name=projectState]' ,function(){
var currentState = $('option:selected', this).val();
$('#projectState').val(currentState);
//Remove the old table records and the datatables. Order matters, otherwise there is unsual behavior.
if( $.fn.DataTable.isDataTable( '#searchTable' ) ) {
window.table.destroy();
window.table = null;
}
$('.projectStateText').html( currentState );
//Get the new table records
ajaxLoadTable( *some undisclosed URL*, '#searchTable');
});
I need to change rendering of cell based on the element position, without changing data,
In docs I found mData and mRender options, I tried with fnRender (which is depricated), but it gives me position, but changes data in table while rendering, so I wonder if here is any way to get the cell position when it renders, or I should to rerender table myself after each change ?
the following code illustrate my needs:
$(document).ready( function() {
var oTable = $('#example').dataTable( {
"aoColumnDefs": [ {
"aTargets": ['_all'],
"mRender": function ( data, type, full )
{
if (type!='display') return data;
//HOW to get current cell indexes or DOM element here ?
console.log(this,data,type,full);
return data+' ttt';
}
} ]
} );
$('#example > tbody > tr').on('click','td',function() {
console.log(this);
var pos=oTable.fnGetPosition(this);
var value=oTable.fnGetData(this);
oTable.fnUpdate(value.split("").reverse().join(""),pos[0],pos[2]);
});
var button=$('<button>').text('clickme');
button.click(function() { console.log(oTable.fnGetData());});
$('body').append(button);
});
http://live.datatables.net/enirid/3/edit
the sample using fnRender:
$(document).ready( function() {
var oTable = $('#example').dataTable( {
"aoColumnDefs": [ {
"aTargets": ['_all'],
"fnRender": function ( obj, data )
{
console.log(obj,data);
var col=obj.iDataColumn;
//HOW to change display here without changing data of table
return data+' '+col;
}
} ]
} );
$('#example > tbody > tr').on('click','td',function() {
console.log(this);
var pos=oTable.fnGetPosition(this);
var value=oTable.fnGetData(this);
oTable.fnUpdate(value.split("").reverse().join(""),pos[0],pos[2]);
});
var button=$('<button>').text('clickme');
button.click(function() { console.log(oTable.fnGetData());});
$('body').append(button);
});
http://live.datatables.net/opubaj/edit
Try fnCreatedCell.
Attached the example code snippet provided from datatables.net:
$(document).ready( function() {
$('#example').dataTable( {
"aoColumnDefs": [ {
"aTargets": [3],
"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
if ( sData == "1.7" ) {
$(nTd).css('color', 'blue')
}
}
} ]
});
} );
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.