DataTables' Autofill extension - column disabling not working - datatables

I am using the Datatables plugin with the Autofill extension with input elements as outlined here:
DataTables' Autofill extension with input elements not working.
This works well. However, I am unable to disable the autofill for specific columns. When I use the "enable": false option, and set it to specific columns, then the callbacks stop working. Does anyone know if there is a way to disable certain columns for autofill, while still allowing the callbacks to function properly? The following disables cols 1-4, but the read/write/step functions no longer copy edited input values:
new $.fn.dataTable.AutoFill(table, {
"columnDefs": [{
"targets": [5, 6, 7, 8, 9],
"read": function (cell) {
return $('input', cell).val();
},
"write": function (cell, val) {
return $('input', cell).val(val);
},
"step": function (cell, read, last, i, x, y) {
return last === undefined ? read : last;
},
"enable": false, "targets": [1,2,3,4] //omitting this leaves all columns enabled.
}]
});

The way you've written it, you are defining the targets property twice in the same object. What you need to do is to give columnDefs another object pointing to the other targets. Like so:
new $.fn.dataTable.AutoFill(table, {
columnDefs: [
{
targets: [5, 6, 7, 8, 9],
read: function (cell) {
return $('input', cell).val();
},
write: function (cell, val) {
return $('input', cell).val(val);
},
step: function (cell, read, last, i, x, y) {
return last === undefined ? read : last;
}
},
{
targets: [1,2,3,4],
enable: false
}
]
});

Related

Button onClick inside DataTables doesn't show the correct url

I'm displaying all the customer data using DataTables like this:
<script type="text/javascript" src="DataTables/datatables.min.js"></script>
<script>
var theTable = null;
$(document).ready(function() {
theTable = $('#table-customer').DataTable({
"processing": true,
"serverSide": false,
"ordering": true,
"order": [[ 0, 'asc' ]],
"ajax":
{
"url": "http://localhost/myshop/showdata.php",
"type": "GET"
},
"sAjaxDataProp": "data",
"deferRender": true,
"aLengthMenu": [[5, 10, 20, 50],[ 5, 10, 20, 50]],
"columns": [
{ data: "cust_id" },
{ data: "cust_name" },
{ data: "cust_addr" },
{ data: "cust_email" },
{ data: "cust_phone" },
{ data: "cust_photo", sortable: true, render: function (o) { return '<button id="btn1" onclick="displayImage(data)">Show</button>';}
]
});
});
function displayImage(link){
window.alert(link);
}
</script>
All information is displayed properly, except 1 thing: if you click any button on "customer photo" column, instead of showing an alert which shows its URL, nothing happens. Inspecting the page showed me this:
Uncaught ReferenceError: data is not defined
at HTMLButtonElement.onclick (view.html:1)
How to fix this?
The columns.data render function builds a string which is returned:
function (o) { return 'your string here, including data value'; }
You have to (a) concatenate your data variable with the string literals you need; and (b) use the variable name you provided - I will use data instead of o:
function (data) { return 'your string here, including ' + data + ' value'; }
So, if we provide all the possible parameters allowed in the renderer, that becomes:
{
"data": "cust_photo",
"sortable": true,
"render": function(data, type, row, meta) {
return '<button id="btn1" onclick="displayImage(\'' + data + '\')">Show</button>';
}
}
I use \' to ensure the value of the data variable is surrounded in single quotes.
(Note that in your question, the code is also missing a closing }.)
But to avoid potential issues with sorting and filtering, these column data render functions need to account for DataTable's use of orthogonal data.
The type parameter can be used for this:
{
"data": "cust_photo",
"sortable": true,
"render": function(data, type, row, meta) {
if (type === 'display') {
return '<button id="btn1" onclick="displayImage(\'' + data + '\')">Show</button>';
} else {
return data; // type is for sorting or filtering - just use the raw value
}
}
}

Datatables - passing one data of the selected row to a modal

I have a datatable that has an edit button on each row. When I click the edit button, a function opens a modal to display the data of the selected record.
Initially, I just want to get the id(which I referred to as PID) of the selected record. However according to my code, I am not sure how to extract the value passed. I kept on getting undefined response.
Please advise on any errors in my code or is there a better way to do this.
Thanks
select: true,
ajax: {
url: "people-grid-data.php",
type: "POST",
},
columnDefs: [{
"targets": [3, 4, 6, 7, 8, 9],
"visible": false,
"searchable": true
},
],
columns: [
{
"width":"2%",
"render": function (data, type, full, meta) {
return "<button type='button' class='btn btn-xs' data-toggle='modal' data-target='#editPersonModal'>Edit </button>";
},
},
{
"data": "PID",
render: getImg
},
{
"data": "PID"
},
{
"data": "personName"
},
{
"data": "PeopleRemarks"
}
],
"order": [
[2, 'asc']
]
});
$('#editPersonModal').on('show.bs.modal', function (data, type, full, meta) {
console.log("Data ID---"+data['PID']);
});
i have a button in my grid , you open your modal with this, using data atributes
render: function (data, type, row) {<a data-info="' + row.IdUser + '" data-toggle="modal" data-target="#modalGridTable" ...
in row.IdUser i have my id. now when i click in $('#modalGridTable').on('show.bs.modal', function (event)...
var button = $(event.relatedTarget);
var id = button.data('info');
var data = Grid.ajax.json().data;
function getDataJson(IdUsuario) {
return data.filter(
function (data) {
return data.IdUser === IdUser;
}
);
}
var result = getDataJson(id);
so you can read this example:
result[0].Phone

Order DataTables by invisible data column using columns.orderData

For my question I have prepared a simple test case at JS Bin.
In a word game I am trying to display the 20 longest words played by a player.
I deliver the data from PostgreSQL to DataTables jQuery plugin in JSON format. It is already sorted by word length and by the date when words were played.
This order is stored as numeric value (1, 2, 3, ...) in the row property of each JSON object:
var dataSet = [
{"row":4,"gid":1,"created":"25.02.2017 14:07","finished":null,"player1":2,"player2":1,"score1":30,"score2":52,"female1":0,"female2":0,"given1":"Abcde3","given2":"Ghijk4","photo1":null,"photo2":null,"place1":null,"place2":null,"word":"ZZ","score":11},
{"row":2,"gid":1,"created":"25.02.2017 14:07","finished":null,"player1":2,"player2":1,"score1":30,"score2":52,"female1":0,"female2":0,"given1":"Abcde3","given2":"Ghijk4","photo1":null,"photo2":null,"place1":null,"place2":null,"word":"BBBBB","score":6},
{"row":3,"gid":1,"created":"25.02.2017 14:07","finished":null,"player1":2,"player2":1,"score1":30,"score2":52,"female1":0,"female2":0,"given1":"Abcde3","given2":"Ghijk4","photo1":null,"photo2":null,"place1":null,"place2":null,"word":"ABC","score":7},
{"row":1,"gid":1,"created":"25.02.2017 14:07","finished":null,"player1":2,"player2":1,"score1":30,"score2":52,"female1":0,"female2":0,"given1":"Abcde3","given2":"Ghijk4","photo1":null,"photo2":null,"place1":null,"place2":null,"word":"XYZXYZXYZ","score":6}
];
Here is my JavaScript code, where I try to sort the column word (column 2) by the invisible column row (column 0):
function renderGid(data, type, row, meta) {
return (type === 'display' ? '<IMG SRC="https://datatables.net/examples/resources/details_open.png"> #' + data : data);
}
function renderGame(data) {
return 'Details for game #' + data.gid;
}
jQuery(document).ready(function($) {
var longestTable = $('#longest').DataTable({
data: dataSet,
order: [[2, 'desc']],
columns: [
{ data: 'row', orderable: false, visible: false },
{ data: 'gid', orderable: false, visible: true, className: 'details-control', render: renderGid },
{ data: 'word', orderable: true, visible: true, orderData: 0 /* order by invisible column 0 */ },
{ data: 'score', orderable: false, visible: true }
]
});
$('#longest tbody').on('click', 'td.details-control', function () {
var img = $(this).find('img');
var tr = $(this).closest('tr');
var row = longestTable.row(tr);
if (row.child.isShown()) {
row.child.hide();
img.attr('src', 'https://datatables.net/examples/resources/details_open.png');
} else {
row.child( renderGame(row.data()) ).show();
img.attr('src', 'https://datatables.net/examples/resources/details_close.png');
}
});
});
However this does not work - the displayed words order is ZZ, BBBB, ABC, XYZXYZXYZ (seemingly unsorted) - while it should be XYZXYZXYZ, BBBB, ABC, ZZ (sorted by row descending):
Why does not sorting work even though I have specified columns.orderData: 0?
And why can't I change ordering by clicking the greyed out arrows (shown by the red arrow in the above screenshot)?
Ok, this seems to be an old bug in dataTables jQuery plugin: the integer argument is not accepted.
I have to change it to an array with the single value:
{ data: 'word', orderable: true, visible: true, orderData: [0] },
and then it works:

How to define Columndefs after DataTables initialization

Currently I'm using DataTables in each page initializing them individually like this.
var table = $('#' + '<%= gvReports.ClientID %>').DataTable({
"responsive": true,
"bAutoWidth": true,
"oLanguage": {
"sSearch": "Search Table: ",
"sSearchPlaceholder": "Search records",
"sEmptyTable": "No data available to display"
},
"columnDefs": [
{
"targets": [0],
type: 'natural-nohtml'
}
],
"sScrollY": "55vh",
"scrollCollapse": false,
"pagingType": "full_numbers",
"lengthMenu": [[25, 50, 100, 150, 200], [25, 50, 100, 150, 200]]
});
When I tried to create a generic JQuery method to use in multiple places the type attribute in columnDef is not working properly
"columnDefs": [
{
"targets": [0],
type: 'natural-nohtml'
}
],
Im using NatualSort plugin to sort the data as the column '0' contains alphanumeric data.
Is there a way i can set the columnDefs dynamically? or to set the ColumnDef Type for Column(0) after I initialize the table?
Something Like
table.column("0:visible").Type('natural-nohtml');
Any help is appreciated? I want to know if I'm thinking in right way?
There is no way that you can manipulate columnDefs after the dataTable is initialised. However, when you basically just want to set natural-nohtml as type for the first column for any dataTable, then you could simply extend $.fn.dataTable.defaults. Declare this before you initialise any dataTable :
$.extend( true, $.fn.dataTable.defaults, {
columnDefs: [
{ targets: [0], type: 'natural-nohtml' }
]
} );
This will set any dataTables' first column to type natural-nohtml.

datatables with fixedheader: row click function giving error on fixed cols

I have an on click function storing the row data in the console log
if you click on the first two columns, you'll notice the function returns undefined, however any of the unfrozen columns returns the data object
I know that this has todo with the fact that the fixedcolumns are created in a cloned table, i was wondering if there was any workaround to this?
// Server-side processing with object sourced data
var $table;
$(document).ready(function() {
$table = $('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "/ssp/objects.php",
dom: "<'row'<'col-md-6 'l><'col-md-6 pull-right'>r>t<'row'<'col-md-6'i><'col-md-6'p>>",
"columns": [
{ "data": "first_name" },
{ "data": "last_name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "start_date" },
{ "data": "salary" }
],
scrollY: "600px",
scrollX: "100%",
scrollCollapse: true,
"pageLength": 5,
lengthMenu: [[5, 10, 25, 50 ], [5, 10, 25, 50]],
order: [[ 1, "asc" ]],
} );
new $.fn.dataTable.FixedColumns( $table, {
leftColumns: 2
} );
$table.on("click", "tr",function(){
var aData = $table.row( this ).data();
console.log( aData);
} );
} );
here is my example code in action
You can use fnGetPosition to get information about row index.
From the manual:
This function is functionally identical to fnGetPosition in
DataTables, taking the same parameter (TH, TD or TR node) and
returning exactly the the same information (data index information).
The difference between the two is that this method takes into account
the fixed columns in the table, so you can pass in nodes from the
master table, or the cloned tables and get the index position for the
data in the main table.
Your code needs to be modified as follows:
var fc = new $.fn.dataTable.FixedColumns( $table, {
leftColumns: 2
});
$table.on("click", "tr", function(){
var aData = $table.row(fc.fnGetPosition(this)).data();
console.log(aData);
});
See this example code for demonstration.