javascript Datatable.js how to show value based on previous column - javascript

I am using datatables.js from datatables.net and trying to show a column based on prev col. Like if prev col has got value < 0 then Dr else CR.
I have tried the following script:
$(document).ready(function() {
var oTable = $('#transaction-list-results').dataTable( {
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"bProcessing": true,
"sAjaxSource": "ajax/transactions.php",
"aaSorting": [[0, 'asc']],
"bAutoWidth": false,
"aoColumns": [
{ "mData": "ref_no", 'sWidth': '100px' },
{ "mData": "date", 'sWidth': '100px', "mRender": function(data, type, row){return localizeDateStr(data);}},
{ "mData": "desc", 'sWidth': '300px' },
{ "mData": "amount", 'sWidth': '75px', "sCalss": 'amount' },
{ "mData": "depo", 'sWidth': '75px', "mRender": function(data, type, row){return data;}},
{ "mData": "width", 'sWidth': '75px', "mRender": function(data, type, row){return data;}},
{ "mData": "transfer", 'sWidth': '75px', "mRender": function(data, type, row){return data;}}
]
} );
} );
Result of my transaction.php file:
{"aaData":[{"ref_no":"4345643532","date":"2012-10-09T17:36:28Z","desc":"Western Union","amount":-50,"depo":"","width":"","transfer":""},{"ref_no":"4324","date":"2012-10-09T17:28:06Z","desc":"123","amount":-10,"depo":"","width":"","transfer":""},{"ref_no":"4324","date":"2012-10-09T17:27:48Z","desc":"123","amount":3.45,"depo":"","width":"","transfer":""},{"ref_no":"123","date":"2012-10-05T20:56:11Z","desc":"abc","amount":10,"depo":"","width":"","transfer":""},{"ref_no":"12","date":"2012-10-01T16:47:19Z","desc":"autorefill","amount":2000,"depo":"","width":"","transfer":""}]}

So, you actually are already using some functions here that should help.
mRender will allow you render the data displayed in a particular column, defined in your aoColumns definition. You correctly have the three arguments labeled for the function:
data (the data for the cell, based on the mData key)
type
row (the dataset for the entire row)
So you can do something like this:
...
"mRender": function(data, type, row) {
var valueToCompare = row.someOtherCell
returnValue = data;
if (data > valueToCompare) { // or some similar logic
returnValue = somethingElse;
}
return returnValue;
}
...
Also, as a side note - you use mRender several times just to return data. That's not necessary if you're not manipulating the value - this is implicitly done through simply setting the mData property.

Related

How to manage datatable for large data

I have a datatable for report. When i tried to show my datas, My browser freezed or crashed. My js code on below
Reporting_Report.DTReport = $('#Report-ReportTable').DataTable({
"ajax": {
"url": "/Ajax/JsonProvider?Method=HardwareHostScreenUsage&GenericObject=true&Json=" + JSON.stringify(json),
"dataSrc": ""
},
"columns": [
{
"data": "BranchName",
"sTitle": "BranchName"
},
{
"data": "HardwareHostFriendlyName",
"sTitle": "Hardware Host Friendly Name"
},
{
"data": "HardwareHostScreenUsageScreenState",
"defaultContent": "N/A",
"sTitle": "Hardware Host Screen Name"
"render": function(data, type, full) {
if (data && Util.Check.IsInteger(data)) {
if (data == 1) {
return "Sorry Screen";
} else if (data == 2) {
return "Welcome Screen";
} else if (data == 3) {
return "Progress Screen";
}
}
}
},
{
"data": "HardwareHostScreenUsageSecondOnScreen",
"sTitle": "Elapsed Time On Hardware Host Screen"
},
{
"data": "HardwareHostScreenUsageRecordDate",
"sTitle": "Hardware Host Screen Usage Record Date"
"render": function (data, type, full) {
return Util.JsonDateToDate(data).format("dd.mm.yyyy HH:MM:ss");
}
}
],
"pageLength": 20,
"lengthMenu": [
[20, 50, 100, -1],
[20, 50, 100, "All"]
],
"info": false,
bFilter: true,
bInfo: false,
"order": [[0, "asc"]],
"scrollX": true,
dom: 'Bfrtip',
buttons: [
{
extend: 'copy'
},
{
extend: 'csv'
},
{
extend: 'excel'
},
{
extend: 'pdf',
title: "Detailed Ticket Report"
message: startDate + " " + startTime + " - " + endDate + " " + endTime + "\t" + datetime,
pageSize: 'LEGAL'
},
{
extend: 'print'
}
]
});
I have more than 100.000 datas.
I thinked maybe i can just get showing page datas and total data number(for manage page numbers) and when clicked another page number send new query and get new datas. But i couldn't find how to do that to.(maybe it cause some another problems (shorting, searching vs.)
Have you got any ideas and solutions.(or this problem has already a solution)
footnote:json has some filters for query(time, branch, etc.)
HardwareHostScreenUsage method gets my datas on c# side.
you can use client side data source also-
var mydata = [];
$('#example').DataTable({
data: data,
deferRender: true,
scrollY: 200,
scrollCollapse: true,
scroller: true
});
fetch all data at once from server and show it while scrolling the table .
You Need these library -
https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js
https://cdn.datatables.net/scroller/1.4.3/js/dataTables.scroller.min.js

Datatables - Refresh/Reload ajax not working

Hi folks I was able to sucessfully create a datatable that would get it's data from an ajax call. So for the initial loading is working fine. I created a button called refresh and I was hoping that if I call my function initiatearchiveIncidents it would go and fetch my data again and reload the table but instead im getting the error cannot re-initialise the Datatable.
So I tried doing dtTable.ajax.reload(); but this fails because it dosent understand my ajax call. Would anyone know how to do this properly?
initiatearchiveIncidents: function () {
$.getJSON(this.basePath() + '/XPROD_Incidents?$filter=ÉtatValue%20eq%20%27Fermé%27&$orderby=Modifié asc',
function (data) {
//Sharepoint REST returns a nested data format, so we go deep to get the useful parts
var myData = data.d.results;
moment.locale('fr');
//this is the key part of datatables
dtTable = $('#example').DataTable({
data: myData,
columns:[
{
"width": "30px",
sortable: false,
"render": function (data, type, full, meta) {
return "<button class='edit_button btn btn-default btn-sm' name ='btnSubmit' type='button' value='Edit' data-ID='"+full.ID+"'><i class='fa fa-pencil fa-2'></i></button>";
}
},
{ data: "Incident", "width": "75px" },
{
"width": "65px",
sortable: false,
"render": function (data, type, full, meta) {
return "<h4><span class='priorité_span'>"+full.PrioritéValue+ "</span></h4>";
}
},
{ data: "Composante","width": "75px",className: "over_flow_control" },
{ data: "Description","width": "300px",className: "over_flow_control" },
{ data: "Début_imputabilité","width": "100px" },
{ data: "ResponsableValue","width": "100px",className: "over_flow_control" }
],
"order": [[ 5, "desc" ]],
"drawCallback": function( settings ) {
IncidentManager.table_conditional_format();
$('#loading').hide("slow");
},
})
});
},
You need to rewrite your initiatearchiveIncidents() function to use jQuery DataTables Ajax functionality with ajax.url and ajax.dataSrc options, see below.
When you need to reload the data, just call $('#example').DataTable().ajax.reload(), see ajax.reload() for more details.
initiatearchiveIncidents: function() {
moment.locale('fr');
//this is the key part of datatables
dtTable = $('#example').DataTable({
ajax: {
url: this.basePath() + '/GDI_PROD_Incidents?$filter=ÉtatValue%20eq%20%27Fermé%27&$orderby=Modifié asc',
dataSrc: "d.results"
},
columns: [
{
"width": "30px",
sortable: false,
"render": function(data, type, full, meta) {
return "<button class='edit_button btn btn-default btn-sm' name ='btnSubmit' type='button' value='Edit' data-ID='" + full.ID + "'><i class='fa fa-pencil fa-2'></i></button>";
}
}, {
data: "Incident",
"width": "75px"
}, {
"width": "65px",
sortable: false,
"render": function(data, type, full, meta) {
return "<h4><span class='priorité_span'>" + full.PrioritéValue + "</span></h4>";
}
}, {
data: "Composante",
"width": "75px",
className: "over_flow_control"
}, {
data: "Description",
"width": "300px",
className: "over_flow_control"
}, {
data: "Début_imputabilité",
"width": "100px"
}, {
data: "ResponsableValue",
"width": "100px",
className: "over_flow_control"
}
],
"order": [[5, "desc"]],
"drawCallback": function(settings) {
IncidentManager.table_conditional_format();
$('#loading').hide("slow");
}
});
},

Adding html.actionLink to Jquery Datatable

want to add HTML.actionlink to Jquery Datatable.
Am wokrking on this existing site made by someone else. For adding data they used Jquery Datatable with is new to me.
This is the data table:
this.oUserList = $('#UserList').dataTable({
"bLengthChange": false,
"bSort": true,
"bRetreive": true,
"bDestroy": true,
"aaSorting": [[0, "asc"]],
"bProcessing": true,
"sAjaxSource": "#Url.Action("GetUsers","Users")",
"sAjaxDataProp": "Result",
"aoColumns": [
{ "mDataProp": function(source, type, val) {
return source.FirstName + ' ' + source.LastName;
}, "bSortable": true },
{ (1st column },
{ 2ndcolumn},
{
3rd column
}, "bSortable": false },
{
4th column
}, "bSortable": false
},
{
5th column
}, "bSortable": false
},
Here is where i want to change it to action link
{ (6th)
"mDataProp": function (source, type, val) {
return M2.JsonDateToString(source.DateLastLogin);
}, "bSortable": false
},
My 6th column is a duplicate of the 5th, but what i need here is an action link, like this: (How i normally implement them):
<td>#Html.ActionLink("Edit Roles", "Edit", "Users", new { userName = "User\\" + u.UserName }, new { #class = "action" }) </td>
So what I want to no is how do you add a html actionLink to a Jquery Datatable.
Use the source json object to build the anchor:
this should work
{
"mDataProp": function (source, type, val) {
return 'Edit Roles'
}, "bSortable": false
},
Use this article www.codeproject.com/Articles/155422/jQuery-DataTables-and-ASP-NET-MVC-Integration-Part

Reload dataTables after button click

I'm sure there are a few (better) ways to do this, but I can't get any way to work. I'm trying to have datatables load new data (from different data source) when a button is clicked.
Here's what I have:
$(document).ready(function() {
$('#datatable2').dataTable( {
"ajax": {
"url":"simple4.php",
"type":"GET"
} ,
"paging": true,
"pageLength": 20,
"order": [[ 2, "asc" ]],
"aoColumns": [
{ "bSortable": false, "width": "25%" },
{ "bSortable": true, "width": "30%" },
{ "bSortable": true, "width": "15%" },
{ "bSortable": true, "width": "15%" },
{ "bSortable": true, "width": "15%" },
{ "bSortable": false, "width": "0%", "visible":false },
],
});
$( "#option2" ).click(function() {
table.ajax.url( 'simple3.php' ).load();
});
});
The initial table (from simple4.php) loads fine. I'd like it to change when I click on a button (with id=option2 in this case), but nothing happens when I click the button.
Just in case, here's the button code in case I'm missing something obvious:
<label class="btn btn-default">
<input type="radio" name="options" id="option2" value="1" autocomplete="off"> Compare 1 and 2
</label>
Not sure what the issue is. Any insight would be helpful.
UPDATE: see answers below explanation of the issue. One thing I didn't do, which apparently makes a major difference is using "dataTable" versus "DataTable". You need a capital D and capital T. Here's the fixed code that's working now:
$(document).ready(function() {
var table = $("#datatable2").DataTable({
"ajax": {
"url":"simple3.php",
"type":"GET"
} ,
"paging": true,
"pageLength": 20,
"order": [[ 2, "asc" ]],
"aoColumns": [
{ "bSortable": false, "width": "25%" },
{ "bSortable": true, "width": "30%" },
{ "bSortable": true, "width": "15%" },
{ "bSortable": true, "width": "15%" },
{ "bSortable": true, "width": "15%" },
{ "bSortable": false, "width": "0%", "visible":false },
],
});
$( "#option2" ).click(function() {
table.ajax.url( "simple4.php" ).load();
});
});
One more thing...my function that was supposed to fire when I clicked on my radio button wasn't working. Had to change from this:
$( "#option2" ).click(function() {
table.ajax.url( "simple4.php" ).load();
});
To this:
$('input[id=option2]').change(function(){
table.ajax.url( "simple4.php" ).load();
});
First, as the others have said the variable 'table' is not set.
Second, when you call
var table = $('#datatable2').dataTable({.....})
You are returning a jQuery object that won't have access to any of the DataTables API
To get a DataTables API instance you need to make a call like this:
var table = $('#datatable2').DataTable({....});
This should work, assuming that your data returned by your url is properly formed.
Source: https://datatables.net/faqs/#api
I can't try this now, but I think it gonna work:
var table = $('#datatable2').dataTable({...});
$( "#option2" ).click(function() {
table.ajax.url( 'simple3.php' ).load();
});
you are not setting var table = ... so when you call table.ajax... table var does not exists

Bind dynamically created JSON object to JQUERY data table

How to bind dynamic JSON object to jquery data table. Did anyone worked on such scenario.
For example,
var objTable = jQuery.parseJSON(result);
if objTable != null && objTable .length > 0) {
$('#tblName').dataTable({
"bDestroy": true,
"bScrollCollapse": true,
"bJQueryUI": true,
"bPaginate": false,
"sScrollY": "310px",
"bInfo": true,
"bFilter": true,
"bSort": true,
"aaData": objTable,
"aoColumns": [
{ "mData": "Field1" },
{ "mData": "Field2" },
{ "mData": "Field3" },
.
.
.
.
{ "mData": "FieldN" }] //These are dynamically created columns present in JSON object.
});
}
Its possible to add the data to datatable dynammically
Like this
$('#YourTableID').dataTable().fnAddData([sno,msg.json[i].unit_id,msg.jsoni].date_time,msg.json[i].sms_number,msg.json[i].message]);
Befor that you have 5 headers in table for appending above

Categories