Sorting on a column in removing html contents in Datatables 1.10 - javascript

I am unsing datatable 1.10, In my code in one of the column as per the requirement I am adding an HTML checkbox tag.
Now first time when the table gets rendered it shows me those checkboxes but when I click on that column to sort or any other column for sorting then the column which contains HTML contains are getting wiped out. (I crosschecked this with the chrome DOM inspector... the td element contains nothing :()
Below is my dataTable initialization code.
dataTableOptions: function() {
return {
"orderable": true,
"columnDefs": undefined,
"autoWidth": true,
"deferRender": true,
"data": undefined
};
},
dtRowGroupingOptions: function () {
return {
bExpandableGrouping: true,
bExpandSingleGroup: false,
iExpandGroupOffset: -1,
asExpandedGroups: [""]
};
}
var dataTablesOptions = self.dataTableOptions();
dataTablesOptions.data = tableData;
dataTablesOptions["paginate"] = false;
dataTablesOptions["lengthChange"] = false;
dataTablesOptions["columnDefs"] = [{"targets": 0, "data": "serverName", 'title' : 'ServerName'},
{"targets": 1, "data": "COMMAND", 'title' : 'Command'},
{"targets": 2, "data": "PID", 'title' : 'Process Id'},
{"targets": 3, "data": "SIZE", 'title' : 'Size'},
{"targets": 4, "data": "USER", 'title' : 'User'},
{"targets": 5, "data": "action", 'title' : 'Actions', "type" : "html", "orderDataType": "dom-checkbox"}
];
dataTablesOptions["createdRow"] = function (nRow, aData, iDataIndex) {
var self = this;
if (aData["comments"] && aData["comments"].indexOf("Error") != -1) {
// Do not do anything
$('td:eq(0)', nRow).html(aData["serverName"]+"" +
"<a class='btn btn-danger' href='#' data-toggle='tooltip' title='Error in execution'><i class='icon-question'></i></a>");
}
return self;
};
var dcInfoDataTable = contentDiv.find('table.dcInfoTable').DataTable(dataTablesOptions);
I am also using datatables rowGrouping and searchhiglight plugin, below is the code.
// call row grouping
contentDiv.find('table.dcInfoTable').dataTable().rowGrouping(self.dtRowGroupingOptions());
// enable search highlighing
contentDiv.find('table.dcInfoTable').dataTable().fnSearchHighlighting();
Note: I tried removing rowGrouping plugin code just to make sure that this is not happeing because of this plugin but even after removing there is no effect, the HTML contents are getting wiped out.

Not only when you sort will it clear out your data, it will also clear it if you use any other feature that changes your table. This happens because each time the datatable draws for new data, it's clearing out your static data.
You need to re-append the checkboxes on each draw, you can do this in the fnDrawCallback event:
$(document).ready( function() {
$('#example').dataTable( {
"fnDrawCallback": function( oSettings ) {
alert( 'DataTables has redrawn the table' );
//append the checkbox to your table columns here...
}
} );
} );

Related

HTML DataTables render a function in the cell

I have a JavaScript function that creates the DataTable. For the first cell in each row, I want to render a vizualisation function (with 3Dmol.js library) and display the object in this cell. The 3Dmol.js requires a container where the function result should be placed (the element variable). I want to choose the current cell. I tried with $(this); but I get an error saying: "Uncaught error creating viewer: TypeError: div.getBoundingClientRect is not a function"
<script type="text/javascript">
var in_json = '{{ in_json }}'
$(document).ready(function () {
$('#fragmenterTable').DataTable({
'ajax': { url: in_json, dataSrc: 'data' },
"scrollX": true,
"scrollY": 200,
"autoWidth": false,
"columnDefs": [
{
"render": function ( data, type, row ) {
return function viz_frag(data) {
var glviewer = null;
data = data
let element = $(this);
glviewer = $3Dmol.createViewer(element, "gldiv");
glviewer.addModel(data,'mol2');
glviewer.setStyle({},{stick:{}});
glviewer.zoomTo()
glviewer.zoom(2,1000);
glviewer.render();
glviewer.setBackgroundColor(0xffffff);
};
},
"targets": 0
},
{ "visible": false, "targets": [ 3 ] }
]
});
$('.dataTables_length').addClass('bs-select');
});
</script>
What am I missing? Thank you!

Datatables: dynamic page load in modal, based on row values

I am trying something really complex here, and I have not worked out a way to implement a solution yet. The part I work on looks like this:
1. simple page A that dynamically loads datatable from db.Last col is a button.
2. an html page B that loads different things according to 2 values stored at at local storage. these are available in the aforementioned table.
Now the part I cannot figure out:
3. Into the simple page A, there is a modal div. I want to load the B page into this modal on button click, and load different data, according to the values stored at local storage.
Here is my code so far:
function getadminprojects(){ //function that dynamically loads datatable
$.ajax({
url: "http://....../CustomServices/DBDistApps",
type: "GET",
dataType: 'json',
async: false,
success: function(data) {
$('#projectsdt').show();
projectsTable = $('#projectsdt').DataTable({
"pageLength": 10,
"data": data,
"scrollX": true,
"order": [[ 4, "desc" ]],
//"aaSorting": [],
"columns": [
{ "data": "code" },
{ "data": "descr" },
{ "data": "manager" },
{ "data": "customer" },
{ "data": "link_date" },
{ "data": "delink_date"},
{ "data": "type"},
{
"data": null,
"defaultContent": "<button class='btn btn-warning' onclick='openmodal2();'>button1</button>"
},
{
"data": null,
"defaultContent": "<button class='btn btn-success' onclick='localStorage.setItem('username',"+row.customer+");localStorage.setItem('projectid',"+row.code+"); projectpopmodal(); '>button2</button>"
},
] ,
});
$('#projectsdt thead').on('click', 'tr', function () {
var data2 = table.row( this ).data();
alert( 'You clicked on '+data2[0]+'\'s row' );
} );
$('#projectsdt').show();
$('#projectsdt').draw();
}
});
}
function projectpopmodal(){
$('#showfreakinmap').load('newprojects.html');
$('#fsModal').modal('show');
}//function to load page B into modal of page A
Thank you in advance!

How to pass values of a column of rows whose checkboxes are selected in jQuery Data Table

I have a datatable which is getting populated by an ajax call. Following is the code:
oTable = $('#lenderList').dataTable(
{
bServerSide: true,
bProcessing: true,
searching: true,
sAjaxSource: "loanAdminAjax?ajax=true&searchCol="+$('#category').val(),
sServerMethod: 'POST',
sPaginationType: "full_numbers",
columnDefs:[
{
targets:8,
checkboxes:{
selectrow:true
}
}
],
aoColumns: [
{
"sName": "loanApplicationNumber",
mData: "loanApplicationNumber"
},
{
"sName": "name",
mData: "name"
},
{
"sName": "submissionDate",
mData: "submissionDate"
},
{
"sName": "kycEmailId",
mData: "kycEmailId"
},
{
"sName": "appVersion",
mData: "appVersion"
},
{
"sName": "documentStatus",
mData: "documentStatus"
},
{
"sName": "latestRemark",
mData: "latestRemark"
},
{
"sName": "appName",
mData: "appName"
},
{
nData: "salaryTransaction",
render: function ( salaryTransaction, type, row ) {
if ( type === 'display' ) {
return '<input type="checkbox" class="editor-active">';
}
return salaryTransaction;
},
className: "dt-body-center"
}
],
dom: '<"button">lfrtip'
}
);
});
I have to consider all the loan application numbers of the respective rows whose checkboxes are checked by the user. So I can trigger an event on Click of a button but how can I get the values of Loan Application Number of those rows whose checkboxes are clicked.
I am new to javaScript. Please let me know how this can be achieved.
I have this idea : Loop through all the rows of the table, and test if the checkbox of that row is checked or not. If it is, then extract the value of the needed cell!
Try this :
$(document).ready(function(){
$("button").click(function(){
oTable = $("#lenderList").dataTable(); // Get the datatable,
var loanApplicationNumbers = []; // An array that will contain the "loan application numbers"
oTable.$('tr').each(function(index,rowhtml){ //Loop through the table rows
//Check the state of the checkbox
var checked= $('input[type="checkbox"]:checked',rowhtml).length;
if (checked==1){
//If the checkbox is checked, then add the inner text of the cell to the array
loanApplicationNumbers.push(rowhtml.children[1].innerText);
}
});
console.log(loanApplicationNumbers); //Do whatever you want
});
});
Note : rowhtml.children is an Array of cells in that row, if you want to get the value of the first cell, you should do rowhtml.children[0].innerText .

JQuery Datatables : Cannot read property 'aDataSort' of undefined

I created this fiddle to and it works well as per my requirements: Fiddle
However, when I use the same in my application I get an error in the browser console saying Cannot read property 'aDataSort' of undefined
In my application, the javascript reads something like as below: I have checked the controller output...it works well and is printed on the console too.
$(document).ready(function() {
$.getJSON("three.htm", function(data) {
// console.log("loadDataTable >> "+JSON.stringify(data));
})
.fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ', ' + error;
alert(err);
console.log( "Request Failed: " + err);
})
.success(function(data){
loadDataTable(data);
});
function loadDataTable(data){
$("#recentSubscribers").dataTable().fnDestroy();
var oTable = $('#recentSubscribers').dataTable({
"aaData" : JSON.parse(data.subscribers),
"processing": true,
"bPaginate": false,
"bFilter": false,
"bSort": false,
"bInfo": false,
"aoColumnDefs": [{
"sTitle": "Subscriber ID",
"aTargets": [0]
}, {
"sTitle": "Install Location",
"aTargets": [1]
}, {
"sTitle": "Subscriber Name",
"aTargets": [2]
}, {
"aTargets": [0],
"mRender": function (data, type, full) {
return '<a style="text-decoration:none;" href="#" class="abc">' + data + '</a>';
}
}],
"aoColumns": [{
"mData": "code"
}, {
"mData": "acctNum"
}, {
"mData": "name"
}]
});
}
})
It's important that your THEAD not be empty in table.As dataTable requires you to specify the number of columns of the expected data .
As per your data it should be
<table id="datatable">
<thead>
<tr>
<th>Subscriber ID</th>
<th>Install Location</th>
<th>Subscriber Name</th>
<th>some data</th>
</tr>
</thead>
</table>
Also had this issue,
This array was out of range:
order: [1, 'asc'],
For me, the bug was in DataTables itself; The code for sorting in DataTables 1.10.9 will not check for bounds; thus if you use something like
order: [[1, 'asc']]
with an empty table, there is no row idx 1 -> this exception ensures.
This happened as the data for the table was being fetched asynchronously. Initially, on page loading the dataTable gets initialized without data. It should be updated later as soon as the result data is fetched.
My solution:
// add within function _fnStringToCss( s ) in datatables.js
// directly after this line
// srcCol = nestedSort[i][0];
if(srcCol >= aoColumns.length) {
continue;
}
// this line follows:
// aDataSort = aoColumns[ srcCol ].aDataSort;
I faced the same problem, the following changes solved my problem.
$(document).ready(function() {
$('.datatable').dataTable( {
bSort: false,
aoColumns: [ { sWidth: "45%" }, { sWidth: "45%" }, { sWidth: "10%", bSearchable: false, bSortable: false } ],
"scrollY": "200px",
"scrollCollapse": true,
"info": true,
"paging": true
} );
} );
the aoColumns array describes the width of each column and its sortable properties.
Another thing to mention this error will also appear when you order by a column
number that does not exist.
In my case I had
$(`#my_table`).empty();
Where it should have been
$(`#my_table tbody`).empty();
Note: in my case I had to empty the table since i had data that I wanted gone before inserting new data.
Just thought of sharing where it "might" help someone in the future!
In my case I solved the problem by establishing a valid column number when applying the order property inside the script where you configure the data table.
var table = $('#mytable').DataTable({
.
.
.
order: [[ 1, "desc" ]],
You need to switch single quotes ['] to double quotes ["] because of parse
if you are using data-order attribute on the table then use it like this data-order='[[1, "asc"]]'
Most of the time it occurs when something is undefined. I copied the code and removed few columns which disturbed the order by index. Carefully make changes and every variable after it.
"order": [[1, "desc"]], fixed my issues previous i was using "order": [[24, "desc"]], and that index was not avaialble.
I had this problem and it was because another script was deleting all of the tables and recreating them, but my table wasn't being recreated. I spent ages on this issue before I noticed that my table wasn't even visible on the page. Can you see your table before you initialize DataTables?
Essentially, the other script was doing:
let tables = $("table");
for (let i = 0; i < tables.length; i++) {
const table = tables[i];
if ($.fn.DataTable.isDataTable(table)) {
$(table).DataTable().destroy(remove);
$(table).empty();
}
}
And it should have been doing:
let tables = $("table.some-class-only");
... the rest ...
I got the error by having multiple tables on the page and trying to initialize them all at once like this:
$('table').DataTable();
After a lot of trial and error, I initialized them separately and the error went away:
$("#table1-id").DataTable();
$("#table2-id").DataTable();
My Solution
add this :
order: 1 ,
For me
adding columns in this format
columns: [
{ data: 'name' },
{ data: 'position' },
{ data: 'salary' },
{ data: 'state_date' },
{ data: 'office' },
{ data: 'extn' }
]
and ajax at this format
ajax: {
url: '/api/foo',
dataSrc: ''
},
solved for me .
Old question, but in my case I was passing an unrelated order= in the URL that would sometimes be empty. Once I changed the url variable to "sortorder" or anything other than "order" the plugin began working normally.
I got the same error, In my case one of the columns was not receiving proper data. some of the columns had strings in place of Integers. after i fixed it it started working properly. In most of the cases the issue is "table not receiveing proper data".
Just my two cents regarding order: [...];
It won't check items type, and in my case I was passing [arrOrders] as opposed to just arrOrders or [...arrOrders], resulting in [[[ 1, "desc" ], [ 2, "desc" ]]].

jquery datatables: adding extra column

Scenario
I am using datatables (#version 1.9.4) for the first time to display data to the user.
I succeed in retrieving the data via ajax and in binding them to the datatable.
Now I want to add extra columns to let the user process the records. For semplicity sake, the aim is to add a button with an onclick handler that retrieve the data of the 'clicked' record.
In my plan I would bind the json item corresponding to the 'clicked' record to the onclick handler.
Till now, if I add an additional TH for the action column to the DOM, an error occurs from datatables code:
Requested unknown parameter '5' from data source for row 0
Question
How to set custom columns? How to fill their content with HTML?
Here is my actual config.
HTML
<table id="tableCities">
<thead>
<tr>
<th>country</th>
<th>zip</th>
<th>city</th>
<th>district code</th>
<th>district description</th>
<th>actions</th>
</tr>
</thead>
<tbody></tbody>
</table>
Javascript
$('#tableCities').dataTable({
"bPaginate": true,
"bLengthChange": false,
"bFilter": true,
"bSort": true,
"bInfo": false,
"bAutoWidth": true
, "bJQueryUI": true
, "bProcessing": true
, "bServerSide": true
, "sAjaxSource": "../biz/GetCitiesByZip.asp?t=" + t
});
Sample Json result
{
"aaData":
[
[
"IT",
"10030",
"VILLAREGGIA",
"TO",
"Torino"
],
[
"IT",
"10030",
"VISCHE",
"TO",
"Torino"
]
],
"iTotalRecords": 2,
"iTotalDisplayRecords": 2,
"iDisplayStart": 0,
"iDisplayLength": 2
}
Edit
Daniel is right. The solution is to set up the custom column in the aoColumnDefs, specifying the mData and the mRender properties. In particular mRender lets to define custom html and javascript.
/* inside datatable initialization */
, "aoColumnDefs": [
{
"aTargets": [5],
"mData": null,
"mRender": function (data, type, full) {
return 'Process';
}
}
]
You can define your columns in a different way
like this
"aoColumns": [
null,
null,
null,
null,
null,
{ "mData": null }
]
or this
"aoColumnDefs":[
{
"aTargets":[5],
"mData": null
}
]
Here some docs Columns
Take a look at this DataTables AJAX source example - null data source for a column
Note that prior to DataTables 1.9.2 mData was called mDataProp. The name change reflects the flexibility of this property and is consistent with the naming of mRender. If 'mDataProp' is given, then it will still be used by DataTables, as it automatically maps the old name to the new if required.
Another solution/workaround could be adding that '5' parameter...
For example adding extra "" to each row
like this:
[
"IT",
"10030",
"VILLAREGGIA",
"TO",
"Torino",
""
],
[
"IT",
"10030",
"VISCHE",
"TO",
"Torino",
""
]
Just in case anyone using a newer version of DataTables (1.10+) is looking for an answer to this question, I followed the directions on this page:
https://datatables.net/examples/ajax/null_data_source.html
Posting this answer here, just to show that where the aoColumnDefs needs to be defined. I got help from this question it self, but I struggled for a while for where to put the aoColumnDefs. Further more also added the functionality for onclick event.
$(document).ready(function() {
var table = $('#userTable').DataTable( {
"sAjaxSource": "/MyApp/proctoring/user/getAll",
"sAjaxDataProp": "users",
"columns": [
{ "data": "username" },
{ "data": "name" },
{ "data": "surname" },
{ "data": "status" },
{ "data": "emailAddress" },
{ "data" : "userId" }
],
"aoColumnDefs": [
{
"aTargets": [5],
"mData": "userId",
"mRender": function (data, type, full) {
return '<button href="#"' + 'id="'+ data + '">Edit</button>';
}
}
]
} );
$('#userTable tbody').on( 'click', 'button', function () {
var data = table.row( $(this).parents('tr') ).data();
console.log(data);
$('#userEditModal').modal('show');
});
} );

Categories

Resources