Datatable aoColumnDefs is not working as expected - javascript

I am facing an issue with Datatable .
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<c:forEach items="${Details.columns}" var="column">
<th>${column.columnTitle}</th>
</c:forEach>
</tr>
</thead>
<tfoot>
<tr>
<c:forEach items="${Details.columns}" var="column">
<th></th>
</c:forEach>
</tr>
</tfoot>
<tbody>
<c:forEach items="${Details.callList}" var="call">
<tr>
<c:forEach items="${call.attributes}" var="attribute">
<td>${attribute.value}</td>
</c:forEach>
</tr>
</c:forEach>
</tbody>
</table>
$("#example1").dataTable({
'sDom': '"top"i',
//"aoColumnDefs": [{ "bSearchable": true, "aTargets": [1] }],
"bPaginate" : true,
"bLengthChange" : false,
//"bFilter" : true,
"bSearchable": true,
"bSort" : true,
"bInfo" : true,
"bAutoWidth" : false,
"iDisplayLength": 5
//}).columnFilter({"aoColumns": [{ "type": "text" }, { "type": "text" }, null]});
}).columnFilter({"aoColumnDefs": [{ "bSearchable": true, "aTargets": [2] }]});
From the above snippet.. i am trying to remove the filter/search for last column alone.
Here "aoColumns" works as expected - It removes the filter in last column as i coded,
However i am unable to use "aoColumns" . Since the columns in this table is dynamic/configurable, so it is tough for me to change the code everytime.
It would be really grateful if anyone can help me here..
Thanks,

This is how I use Datatables and it works like a charm. I don't do sorting at client-side, I do it at server-side using AJAX, but the configuration for the table should be the same except for "bServerSide=true". Let me know if this solves your problem:
var oTable = $('#tblMainTable').dataTable({
"searching": false,
"bStateSave": true,
"fnStateSave": function (oSettings, oData) {
localStorage.setItem('jobTitlesDataTables', JSON.stringify(oData));
},
"fnStateLoad": function (oSettings) {
return JSON.parse(localStorage.getItem('jobTitlesDataTables'));
},
"pagingType": "full_numbers",
"bLengthChange": false,
"bAutoWidth": false,
"iDisplayLength": 2000,
"bServerSide": true, // server side
"sAjaxSource": BASE_URL + "Job/GetJobTitleMappingDTOs", // AJAX URL
"bProcessing": true,
"fnServerData": function (sSource, aoData, fnCallback, oSettings) {
// send data from client-side to server-side
aoData.push({ "name": "IsMapped", "value": $("#bdgIsMapped").data("selected") });
aoData.push({ "name": "IsSearchableOption", "value": $("#bdgIsSearchable").data("selected") });
aoData.push({ "name": "timestamp", "value": new Date().getTime() }); // Added to avoid caching in some IE versions.
oSettings.jqXHR = $.ajax({
"dataType": 'json',
"type": "GET",
"url": sSource,
"data": aoData,
"cache": false,
"success": function (json) {
// shows records count next to the top title
if (json.iTotalRecords > 0) {
$("#resultsDescription").text(" - " + json.iTotalRecords + " rows.");
}
else {
$("#resultsDescription").text(" - No results.");
}
// shows paginator when necessary
if (json.iTotalRecords > json.iDisplayLength) {
$(".dataTables_paginate").show();
}
else {
$(".dataTables_paginate").hide();
}
$("#isFirstSearch").val("false");
fnCallback(json);
}
});
},
"aoColumnDefs": [
{
sType: "numeric",
mData: "RowNumber",
aTargets: [0],
mRender: function (data, type, full) {
// this is for custom rendering a column just in case you need it
// 'full' is the row's data object, and 'data' is this column's data
return '<span class="RowNumber">' + full.RowNumber + '</span>';
}
},
{
sType: "numeric",
mData: "JobTitleId",
aTargets: [1],
mRender: function (data, type, full) {
// 'full' is the row's data object, and 'data' is this column's data
return '<span class="EditableJobTitleId" data-job-title-id="' + full.JobTitleId + '">' + full.JobTitleId + '</span>';
}
},
{
sType: "string",
mData: "JobTitle",
aTargets: [2]
}
],
"order": [[1, "asc"]]
});

Related

Show Check box in every row using JavaScript data table

Using the JavaScript datable get the data with pagination but i have to show checkbox on header and each row. once select the check box get the id of particular row or if select header checkbox get all rows id on server side.
Table :
<table id="tblSavingColl" class="table table-striped table-bordered dt-responsive nowrap" width="100%" cellspacing="0">
<thead>
<tr style="background-color: Mediumseagreen">
<th>#Html.CheckBox("CheckAll") </th>
<th>Shop</th>
<th>Client ID</th>
<th>Sales Month</th>
<th>Control</th>
<th>Entry</th>
<th>TMS</th>
<th>Informed</th>
<th>Posted</th>
</tr>
</thead>
<tbody id="tblData">
</tbody>
</table>
Javascript:
$("#btnList").click(function () {
var Buildingid = $("#BuildingId").val();
var shopid = $("#ShopId").val();
var Post = $("#SelectedValue").val();
$("#tblSavingColl").DataTable({
"processing": true, // for show progress bar
"serverSide": true, // for process server side
"filter": true, // this is for disable filter (search box)
"orderMulti": false, // for disable multiple column at once
"ajax": {
"url": "/Archive/GetArchiveList",
"type": "POST",
data: { buildingid: Buildingid, shopid: shopid, Post: Post },
"datatype": "json"
},
"columnDefs": [{
'targets': 0,
'checkboxes': {
'selectRow': true
}
//"targets": [0],
//"visible": false,
//"searchable": false,
//'render': function (data, type, full, meta) {
// return '<input type="checkbox" name="id[]" value="'
// + $('<div/>').text(data).html() + '">';
//}
}],
" select": {
'style': 'multi'
},
"order": [[1, 'asc']],
"columns": [
{"data": "id","defaultContent": '',"className": 'select-checkbox',"orderable": true},
{ "data": "shopName", "name": "ShopName", "autoWidth": true },
{ "data": "clientID", "name": "clientID", "autoWidth": true },
{ "data": "salesMonth", "name": "salesMonth", "autoWidth": true },
{ "data": "controlTotal", "name": "controlTotal", "autoWidth": true },
{ "data": "totalAmount", "name": "totalAmount", "autoWidth": true },
{ "data": "tms", "name": "tms", "autoWidth": true },
{ "data": "informed", "name": "informed", "autoWidth": true },
{ "data": "posted", "name": "posted", "autoWidth": true },
//{
// "render": function (data, type, full, meta) { return '<a class="btn btn-info" href="/DemoGrid/Edit/' + full.CustomerID + '">Edit</a>'; }
//},
//{
// data: null,
// render: function (data, type, row) {
// return "<a href='#' class='btn btn-danger' onclick=DeleteData('" + row.CustomerID + "'); >Delete</a>";
// }
//},
]
});
});
I have used this javascript url and also tried to use data table
JS url:
<link type="text/css" href="//gyrocode.github.io/jquery-datatables-checkboxes/1.2.12/css/dataTables.checkboxes.css" rel="stylesheet" />
<script type="text/javascript" src="//gyrocode.github.io/jquery-datatables-checkboxes/1.2.12/js/dataTables.checkboxes.min.js"></script>

error 500 on jquery datatables search

i created a table with jquery datatables. when I want to filter my table with search bar, the browser gives me an alert DataTables warning: table id=grid - Ajax error. For more information about this error, please see http://datatables.net/tn/7.
this is my code :
$("#grid").dataTable({
"processing": true, // control the processing indicator.
"serverSide": true, // recommended to use serverSide when data is more than 10000 rows for performance reasons
"info": true, // control table information display field
"stateSave": true, //restore table state on page reload,
"searching": true,
"language": {
"url": "/translate/datatables.fa-IR.json"
},
"lengthMenu": [[10, 20, 50, -1], [10, 20, 50, "All"]], // use the first inner array as the page length values and the second inner array as the displayed options
"ajax": {
"url": serviceBase + "/Auth/Admin/SearchOrders2/",
"type": "GET",
'beforeSend': function (xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + localStorageService.get("authorizationData").token);
}
},
"columns": [
{ "data": "customerContact", "orderable": true },
{ "data": "isDone", "orderable": true },
{
"mRender":
function (data, type, row) {
var xxx = $scope.name1 = $filter("jalaliDateFromNow")(row["createdDate"]);
return "<span>" + $filter("jalaliDateFromNow")(row["orderCreationTime"]); +'</span>';
}, "orderable": true
},
{ "data": "totalPrice", "orderable": true },
{ "data": "count", "orderable": true },
{ "data": "description", "orderable": true },
{
"mRender": function (data, type, row) {
return '<button class="btn btn-sm btn-circle green tooltips" disabled="disabled"><i class="fa fa-check"></i><span>جزئیات</span></button>'
},
"orderable": false
}
],
"order": [[0, "desc"]]
});
which part of my code is wrong?

datatable warning 4 - Requested unknown parameter '0' for row 0, column 0

I am working on datatable and facing this error :
DataTables warning: table id=table - Requested unknown parameter '0'
for row 0, column 0.
I have studied this link and it says that my table column defines in HTML doesn't match with the columns received from server. BUT in my case both are same.
Here is my HTML code :
<table id="table" class="display responsive nowrap" cellspacing="0" width="100%">
<thead style="background-color:#303641;">
<tr>
<th>aNumber</th>
<th>bNumber</th>
<th>cellID</th>
<th>dateTime</th>
<th>duration</th>
<th>imei</th>
<th>imsi</th>
<th>operatorId</th>
<th>mscId</th>
<th>fileId</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Datatable javascript code :
var dataTable = $('#table').DataTable({
"processing": true,
"serverSide": true,
"bFilter": false,
"iDisplayLength": configData,
dom: 'Bfrtip',
buttons: ['colvis', 'print', 'csv', 'excel', 'pdf'],
searching: false,
language: {
buttons: {
colvis: 'Show/Hide Columns'
}
},
"ajax": {
url: "getAdvanceCallAnalysisData.json",
data: function(d) {
return $.extend({}, d, {
"offset": 0,
"newRequest": newReq,
"totalRecords": total,
"lookInCol": "aNumber",
"lookInVal": "43543543",
"fromDate": from_date,
"toDate": to_date,
"callingCellId": "",
"CalledCellId": "",
"cdrType": "",
"smsType": "",
"durationFilter": "",
"selectColumns": "",
"sortCol": "",
"sortType": "",
});
},
type: "POST",
error: function() {
alert("error");
},
complete: function(data) {
total = data.responseJSON.recordsTotal;
newReq = 0;
test(total, newReq);
$("#loading_image").hide();
$(".show_datatable").show();
},
"aoColumns": [{
"mData": "aNumber"
}, {
"mData": "bNumber"
}, {
"mData": "cellID"
}, {
"mData": "dateTime"
}, {
"mData": "duration"
}, {
"mData": "imei"
}, {
"mData": "imsi"
}, {
"mData": "operatorId"
}, {
"mData": "mscId"
}, {
"mData": "fileId"
}]
}
});
you can see that my columns name and numbers match with the columns define in ajax response.
I have done same thing for another table and it was working fine but it shows error here. don't know why !!
json response : (It returns 15 records, I posted only two just to make it short)
{"msg":null,"code":null,"status":null,"data":[{"aNumber":"343","bNumber":"3434","cellID":"410-01-831-14770","dateTime":"2017-08-23 17:27:54.0","duration":419,"imei":"22380831696837","imsi":"35340311428389","operatorId":4,"mscId":"5","fileId":"4"},{"aNumber":"3434","bNumber":"5656","cellID":"410-07-1314-28271","dateTime":"2017-08-23 22:02:15.0","duration":785,"imei":"49776303943255","imsi":"35722667519554","operatorId":1,"mscId":"2","fileId":"5"}],"draw":1,"limit":1000,"recordsFiltered":12,"recordsTotal":12}
The most funny part is it shows the correct records and pagination even it display correct rows (with empty data) in datatable. This ajax call returns 15 records. Please see the image below :
Any idea, what is wrong here ?

Highlight specific row base on content in jquery datatables

I am using jquery datatables.net and I have a table with information. In the one column I have true or false values for whether the user is active or not. I am trying to get it so when the value is false, highlight the value. Right now my code for my table settings looks like this:
//Settings for datatable
$('#userTable').DataTable({
"jQueryUI": true,
"serverSide": true,
"ajax": {
"type": "POST",
url: "/Management/StaffGet",
"contentType": 'application/json; charset=utf-8',
'data': function (data) { console.log(data); return data = JSON.stringify(data); }
},
"columns": [
{ "data": "employeeNumber" },
{ "data": "firstName" },
{ "data": "lastName" },
{ "data": "role" },
{
"data": "active",
},
{
"data": "employeeNumber",
"render": function (data, type, full, meta)
{
return 'Edit | Delete ';
}
}
],
"order": [[ 0, "asc"]],
"paging": true,
"deferRender": true,
"processing": true,
"stateSave": false,
"lengthMenu": [[5, 10, 25, 50, -1], [5, 10, 25, 50, "All"]],
"pageLength": 10,
"pagingType": "simple_numbers",
"searching": false,
"createdRow": function ( row, data, index ) {
if (data[4] == "false" ) {
$('td', row).eq(5).addClass('highlight');
}
}
});`
Then my code for css is:
`<style type="text/css">
td.highlight {
font-weight: bold;
color: red;
}
</style>`
I feel like there is a problem with the setting on the column, any help is appreciated.
Try
$('#userTable').DataTable({
...
"createdRow": function( row, data, dataIndex ) {
//console.log(data[4]);
if ( data[4] == "false" ) {
//console.log($(row).find("td").eq(4).html());
$(row).find("td").eq(4).addClass( 'highlight' );
}},
...
The commented log statements are in there to check you are getting and comparing the correct data.
Tested with datatables 1.10.1

DataTable Error - Cannot read property 'length' of undefined

I am trying to build my DataTable (1.10.5) using an ajax call to a service - http://www.datatables.net/examples/ajax/
Here is my Javascript:
$('#tableexample').DataTable({
"dom": 'C<"clear">lfrtip',
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "../../api/EventTypes/GetAll",
"aoColumnDefs": [
{
"aTargets": [0],
"mData": "Id"
},
{
"aTargets": [1],
"mData": "Name"
},
{
"aTargets": [2],
"mData": "Name"
},
{
"aTargets": [3],
"mData": "Name"
},
{
"aTargets": [4],
"mData": "Name"
}
]
});
Here is my HTML:
<table id="tableexample" class="table table-striped dataTable table-hover">
<thead>
<tr>
<th>Select</th>
<th>Event</th>
<th>Primary Category</th>
<th>Secondary Category</th>
<th>Workflow</th>
</tr>
</thead>
</table>
Here is my error:
Uncaught TypeError: Cannot read property 'length' of undefined
If I look i my jquery.dataTables.js - it says that my data is undefined...
var data = _fnAjaxDataSrc( settings, json );
Can anyone help me out with setting up my ajax call properly to dynamically build my table??
Thanks!
Finally found it!
I needed to make an ajax call and pass the data to "aaData":
$.ajax({
url: '/Portal/api/EventTypes/GetEventWorkflowDefinitions',
type: 'GET',
dataType: 'json',
success: function (data) {
assignToEventsColumns(data);
}
});
function assignToEventsColumns(data) {
var table = $('#tableexample').dataTable({
"dom": 'C<"clear">lfrtip',
"bAutoWidth": false,
"aaData": data,
"aaSorting": [],
"aoColumnDefs": [
{
"aTargets": [0],
"bSearchable": false,
"bSortable": false,
"bSort": false,
"mData": "EventTypeId",
"mRender": function (event) {
return '<input class="childCheck" type="checkbox" id="childCheckBoxes" value="' + event + '">';
}
},
{
"aTargets": [1],
"mData": "EventType"
}
Once I did this...the table build perfectly!

Categories

Resources