Edit jQuery Datatable fields - javascript

I would like to output a bootstrap label for one value of a field in a JQuery dataTable. This fields possible values can be '0' or '1' and depending on the result I want to decide which bootstrap label I want to output in the dataTable. Unfortunately I don't know how I can do this if statement for this case.
My JQuery:
$(document).ready(function() {
$('#accountOverview').dataTable( {
"ajax": {
"url": "/database/accounts.php",
"data": {"action": "selectAccounts"},
"dataSrc": ""
},
"columns": [
{ "data": "email" },
{ "data": "platform" },
{ "data": "coins" },
{ "data": "profitDay" },
{ "data": "playerName" },
{ "data": "tradepileCards" },
{ "data": "tradepileValue" },
{ "data": "enabled" }
],
"autoWidth": false
});
});
I need to use something like this for the result of the "enabled" field:
if(enabled==1) <label class="label label-success">Online</label>
else <label class="label label-error">Offline</label>
HTML Table:
<table id="accountOverview" class="table datatable">
<thead>
<tr>
<th>E-Mail</th>
<th>Platform</th>
<th>Coins</th>
<th>Profit last 24h</th>
<th>Playername</th>
<th>Tradepile Cards</th>
<th>Tradepile Value</th>
<th>Status</th>
</tr>
</thead>
<tbody id="accountList">
<!-- List all accounts -->
</tbody>
</table>
The label needs to be in the field "status" = the last each row.

Following dataTable's "draw" (which happens after AJAX loads your data), you can look up the last td of each row and use wrapInner() to inject the HTML you want. So, in your case, try:
var apply_label=function(){
$('#accountOverview').find('td:last-child').not(':has(.label)').each(function(){
if( this.innerHTML==="1"){
$(this).wrapInner('<span class="label label-success"></span>');
}
else {
$(this).wrapInner('<span class="label label-danger"></span>');
}
});
};
$('#accountOverview').dataTable( {
"ajax": {
"url": "/database/accounts.php",
"data": {"action": "selectAccounts"},
"dataSrc": ""
},
"columns": [
{ "data": "email" },
{ "data": "platform" },
{ "data": "coins" },
{ "data": "profitDay" },
{ "data": "playerName" },
{ "data": "tradepileCards" },
{ "data": "tradepileValue" },
{ "data": "enabled" }
],
"autoWidth": false,
"drawCallback": function( settings ) {
apply_label();
}
});
Notes:
I think you want span (not label).
I think you want .label-danger (not .label-error).
Check it out at http://jsfiddle.net/jhfrench/wrkkbcf1/.

Related

JQuery Datable throwing error for valid "columns" option parameter

Ok so i have a jquery datatable which is structured like this
$(document).ready(function () {
var table = $('#tableContent').DataTable({
"processing": true,
"serverSide": true,
"filter": true,
"ajax": {
"url": "path/to/api",
"type": "POST",
"datatype": "json"
},
"columnDefs": [{
"searchable": false,
"orderable": false,
"targets": 0
}],
"columns": [
null,
{ "data": "data1", "name": "data1", "autoWidth": true },
{ "data": "data2", "name": "data2", "autoWidth": true },
{ "data": "data3", "name": "data3", "autoWidth": true },
{ "data": "data4", "name": "data4", "autoWidth": true },
{ "data": "data5", "name": "data5", "autoWidth": true },
{ "data": "data6", "name": "data6", "autoWidth": true },
{ "data": "data7", "name": "data7", "autoWidth": true }
],
"order": [[1, 'asc']]
});
table.on('order.dt search.dt page.dt', function () {
table.column(0, { search: 'applied', order: 'applied' }).nodes().each(function (cell, i) {
cell.innerHTML = i + 1;
});
}).draw();
});
<table class="tableWrapper" id="tableContent">
<thead>
<tr>
<th>#</th>
<th>data1</th>
<th>data2</th>
<th>data3</th>
<th>data4</th>
<th>data5</th>
<th>data6</th>
<th>data7</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
</tfoot>
</table>
Here is the JSON response to the Api being called
{
"draw":"1",
"recordsFiltered":48,
"recordsTotal":48,
"data":[
{
"data1":"XXXX",
"data2":"XXXX",
"data3":"XXXX",
"data4":"XXXX",
"data5":"XXXX",
"data6":"XXXX",
"data7":"XXXX"
}...
]
}
It throws this error :
"DataTables warning: table id=tableContent - Requested unknown parameter '0' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4" (Attached error message picture)
BUT! shortly after the error is thrown, the data loads in with no issues.
Replacing null with {data:null} seems to get rid of the error but it messes with my index column. What was supposed to be a sequence of 1,2,3,4... is now just a bunch of [object Object]
see image
There is more than one way to get what you want. Here is one way, which uses the internal DataTables index assigned to each row. This assignment is purely sequential: the first row added to the table (from the first data object in your JSON) is index 0 - and so on:
"columnDefs": [ {
"targets": 0,
"render": function ( data, type, row, meta ) {
return meta.row + 1;
}
} ]
You already have a targets: 0 in your sample, so adding in this should be straightforward.
The assigned index will stick to the row, when you sort and filter.
If you want an index which represents where the row is, visually, in the table - that is more complicated (and wouldn't be do-able using server-provided data, of course).

How to add control item to first column of datatable

I have this datatables declaration:
table = $("#table").DataTable({
"ajax": {
"url": '#Url.Action("Search", #ViewContext.RouteData.Values["controller"].ToString())',
"type": "POST",
"data": function(d) {},
"datatype": "json"
},
"language": {
"search": "",
"searchPlaceholder": " Search"
},
"select": {
"style": 'multi'
},
"ordering": true,
"lengthChange": false,
"columns": [{
"data": "",
"targets": 0,
"className": "control",
"orderable": false,
"searchable": false
}, {
"data": function(data, type, row, meta) {
var url = '#Url.Action("Read", #ViewContext.RouteData.Values["controller"].ToString())/' + data.Id;
return "<a href='" + url + "'>" + data.Application + "</i></a>"
},
"name": "Application"
}, {
"data": "Logged",
"name": "Logged",
"render": function(data) {
var d = moment(data).format("YYYY-MM-DD hh:mm:ss");
return d;
}
}, {
"data": "Level",
"name": "Level"
}, {
"data": "Exception",
"name": "Exception"
}, {
"data": "Message",
"name": "Message"
}, {
"data": "UserName",
"name": "UserName"
}, {
"data": "ServerName",
"name": "ServerName"
}, ],
"responsive": {
"details": {
"type": "column"
}
},
"processing": true,
"serverSide": true,
}).columns.adjust().responsive.recalc();
new $.fn.dataTable.FixedHeader(table);
This is my table header declaration:
<thead>
<tr>
<th></th>
<th>Application</th>
<th>Logged</th>
<th>Level</th>
<th>Exception</th>
<th>Message</th>
<th>UserName</th>
<th>ServerName</th>
</tr>
</thead>
The idea is that the first column or target 0 should be where a button sits to expand or collapse the row. However, when I run the application, I get this error
DataTables warning: table id=table - Requested unknown parameter '' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4
Its saying that my column 0 parameter can't be blank. But I am unsure of what I should put inside it.
Also, for some reason the sorting arrow is still appearing for that column even though its disabled. However, the arrow doesn't change or do anything when clicked.
You have 8 columns, but only have data for 7 of them. Because you're using server-side processing and have no data for that row, you need to add "defaultContent": "" to your column option like so:
"columns": [{
"data": "",
"targets": 0,
"className": "control",
"orderable": false,
"searchable": false,
"defaultContent": ""
},
The same can be achived with "data": null but you'll most likely get an [object Object] returned if you don't deal with the null value before it renders.

Add edit/delete icon to row of data populated by JSOn (AjaxCall)

I have an HTML table which is being populated by a JSON (ajax call). In the Edit and Delete columns of the table I need to have an icon to edit or delete the data on each row.
I don't know how to add the icon when the table is populated by the JSON.
Following is my code:
//JSON which is populating the table. Register.js
$(document).ready(function() {
var allRegister = AjaxCall(apiUrl, mthdGetReleasesFullList, null,
{
});
var data=allRegister.responseText;
alert("testing"+ data);
var jsonResponse = JSON.parse(data);
//var table = $('#contact-data').DataTable({
var table = $('#register-data').DataTable({
"data": jsonResponse.data,
"columns": [
{ "data": "ReleaseID" },
{ "data": "ReleaseName" },
{ "data": "DivisionID" },
{ "data": "StatusID" },
],
"order": [[1, 'dsc']]
});
});
Html code for table:
<link rel="stylesheet" href="entity/Register/css/Register.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- Page specific JS -->
<script src="entity/Register/js/Register.js"></script>
<div class="container-full">
<div class="heading-1">
<input type="button" id="btn-AddUser" value="Add Release" style="font-size:14px;color:teal;text-align: left">
<h1>
</h1>
<div class="modular-box-text inset">
<div class="retgister-table-holder">
<h2>Pre-Release Access Register:</h2>
<br>
<div class="register-table" >
<table id="register-data"class="display tablesorter" role="grid" aria-describedby="example_info" style="width: 100%;" cellspacing="0">
<thead>
<tr>
<th>ReleaseID</th>
<th>ReleaseName</th>
<th>DivisionID</th>
<th>StatusIDth>
<th>Edit<th>
<th>Delete </th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>
</div>
You need to work with the render option of the columns objects - documentation here. When you specify the targeted ID of your desired action (i presume it is ReleaseID) you just create more columns with that ID as data object and adjust the column renderer by giving it a custom render method. Since you specified ReleaseID as data, you can re-use that value in the render method as first argument.
In the example below you can see how to achieve this - You can very easily replace Edit and Delete text with <img /> tags referencing the icons you want to have for each action.
// Faking a request
var response = [
{ "ReleaseID": "1",
"ReleaseName": "Release A",
"DivisionID": "10",
"StatusID": "1"
}, {
"ReleaseID": "2",
"ReleaseName": "Release B",
"DivisionID": "9",
"StatusID": "2"
}, {
"ReleaseID": "3",
"ReleaseName": "Release C",
"DivisionID": "9",
"StatusID": "1"
}, {
"ReleaseID": "4",
"ReleaseName": "Release D",
"DivisionID": "10",
"StatusID": "2"
}, {
"ReleaseID": "5",
"ReleaseName": "Release E",
"DivisionID": "11",
"StatusID": "1"
}];
$(document).on('ready', function() {
$('#register-data').dataTable({
"data": response,
"columns": [
{ "data": "ReleaseID" },
{ "data": "ReleaseName" },
{ "data": "DivisionID" },
{ "data": "StatusID" },
{
"data": "ReleaseID",
"render": (data, type, row, meta) => `Edit`
}, {
"data": "ReleaseID",
"render": (data, type, row, meta) => `Delete`
}
],
"order": [[1, 'dsc']]
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet"/>
<table id="register-data"class="display tablesorter" role="grid" aria-describedby="example_info" style="width: 100%;" cellspacing="0">
<thead>
<tr>
<th>ReleaseID</th>
<th>ReleaseName</th>
<th>DivisionID</th>
<th>StatusID</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Thanks for your response.
I used the following to get Edit and Delete buttons to appear on all rows of table
var table = $('#register-data').DataTable({
"data": jsonResponse.data,
"columns": [
{ "data": "ReleaseID" },
{ "data": "ReleaseName" },
{ "data": "DivisionID" },
{ "data": "StatusID" },
{"data":null, "defaultContent": "<button class='btn-Edit'>Edit</button>"},
{"data":null, "defaultContent": "<button class='btn-Delete'>Click!</button>"},
],
"order": [[1, 'dsc']]
});

Use datatable ajax response data to set custom label value

I have used server-side processing data table.
Here is my datatable configuration:
var table = $("#job-table").DataTable({
"ajax": {
"url": "<?php echo url('/getJobs');?>",
"type": "POST",
"data": function (d) {
d.connection = connectionArray,
d.company = companyArray,
d.type = typeArray
}
},
"processing": true,
"serverSide": true,
"columns": [
{ "data": "id" },
{ "data": "job_id" },
{ "data": "type" },
{ "data": "connection_id" },
{ "data": "company_id" },
{ "data": "message" },
{ "data": "total_completion_time" },
{ "data": "date" },
{ "data": "start_time" },
{ "data": "end_time" },
{ "data": "error_time" }
],
"info": false,
"searching": false,
"bLengthChange": false
});
In this datatable ajax response I have passed some another data which I am gonna use to set custom label value.
Right now, I am using same ajax call to set label value. There are two calls one is of datatable and another call for setting label. Both time I am calling same API. but want to know how can I avoid second ajax call?
Is there any way to use data-table ajax call response to set custom label value?
I do something similar. I used the dataFilter callback to handle it.
so given HTML:
<input id="txtOne"/>
<input id="txtTwo"/>
<table id="job-table" class="display"></table>
Serverside code is returning a JSON Serialized object that looks like:
{ ValueOne: "some data",
ValueTwo: "Some more data",
data: [array of data for the table] }
My table definition looks like (notice the dataFilter section):
var table = $("#job-table").DataTable({
"ajax": {
"url": "<?php echo url('/getJobs');?>",
"type": "POST",
"data": function (d) {
d.connection = connectionArray,
d.company = companyArray,
d.type = typeArray
},
// I added this section. It is called before the success callback
// You will have to figure out your parsing at this point because
// each configuration is different so I just put how mine is.
dataFilter: function(response){
var temp = JSON.parse(response);
$("#txtOne").val(temp.ValueOne);
$("#txtTwo").val(temp.ValueTwo);
return response;
}
},
"processing": true,
"serverSide": true,
"columns": [
{ "data": "id" },
{ "data": "job_id" },
{ "data": "type" },
{ "data": "connection_id" },
{ "data": "company_id" },
{ "data": "message" },
{ "data": "total_completion_time" },
{ "data": "date" },
{ "data": "start_time" },
{ "data": "end_time" },
{ "data": "error_time" }
],
"info": false,
"searching": false,
"bLengthChange": false
});

Could not load Datatable with JSON objects

I am trying for pagination from dynamic data. I started using Datatable but I am not able to load Datatable with JSON Objects.
Please find my code below:
function drawTable(data) {
$('#t01').DataTable( {
ajax: {
"aaData": data,
"dataSrc": ""
},
"aoColumns": [
{ "mdata": "UserName" },
{ "mdata": "AppName" },
{ "mdata": "OS" },
{ "mdata": "Changes" },
{ "mdata": "Time" }
]
} );
}
My JSON:
[{
"UserName": "testUser",
"AppName": "mtv_app",
"OS": "android",
"Changes": "tveEnabled : true to false, ",
"Time": "2016-03-22 11:36:09"
}, {
"UserName": "testUser",
"AppName": "mtv_app",
"OS": "android",
"Changes": "tveEnabled : false to true, ",
"Time": "2016-03-22 11:44:11"
},..
My html page:
<table id="t01" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>UserName</th>
<th>AppName</th>
<th>OS</th>
<th>Changes</th>
<th>Time</th>
</tr>
</thead>
</table>
The table is not getting loaded but loading ... appears in table. I have checked, JSON is in correct format.
I edited my code:
function drawTable(data) {
console.log(data);
$('#t01').DataTable( {
"processing" : true,
"data": data,
"columns": [
{ "data": "UserName" },
{ "data": "AppName" },
{ "data": "OS" },
{ "data": "Changes" },
{ "data": "Time" }
]
} );
}
and now my table is loaded with blank columns and I am getting error as:
DataTables warning: table id=t01 - Requested unknown parameter 'UserName' for row 0, column 0.
Your code work fine for me. This is how I used it :
first : I create a json.php who contains the following code :
[{
"UserName": "testUser",
"AppName": "mtv_app",
"OS": "android",
"Changes": "tveEnabled : true to false, ",
"Time": "2016-03-22 11:36:09"
}, {
"UserName": "testUser",
"AppName": "mtv_app",
"OS": "android",
"Changes": "tveEnabled : false to true, ",
"Time": "2016-03-22 11:44:11"
}]
After I create an other page test.php with these following codes :
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" type="text/css" />
<link rel="stylesheet" type="text/css" href="https://www.datatables.net/release-datatables/extensions/TableTools/css/dataTables.tableTools.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js"></script>
</head>
<body>
<table id="t01" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>UserName</th>
<th>AppName</th>
<th>OS</th>
<th>Changes</th>
<th>Time</th>
</tr>
</thead>
</table>
</body>
<script type="text/javascript">
function drawTable(data) {
console.log(data);
$('#t01').DataTable( {
"processing" : true,
"data": data,
"columns": [
{ "data": "UserName" },
{ "data": "AppName" },
{ "data": "OS" },
{ "data": "Changes" },
{ "data": "Time" }
]
} );
}
$(document).ready(function() {
$.ajax({
url: "json.php",
dataType: "json",
success: function(data) {
drawTable(data);
}
});
});
</script>
</html>
And this is the result :
try this, i think this useful
function drawTable(data) {
console.log(data);
$('#t01').DataTable( {
"bProcessing": true,
"bServerSide": true,
"bFilter" : false,
"sAjaxSource": "data.php",//your data source
"columns": [
{ "data": "UserName" },
{ "data": "AppName" },
{ "data": "OS" },
{ "data": "Changes" },
{ "data": "Time" }
]
} );
}

Categories