Manipulate result for dataTable field - javascript

I would like to output a bootstrap label for one value of a field in a JQuery dataTable. The fields possible values can be '0' or '1' and depending on this result I want to decide which bootstrap label I want to output in the dataTable. I wonder how I can realize the if statement depending on the result of the field "enabled" and how I can fill the field with my html code:
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>

You can add a class to your <td class="enabled>
DUMMY HTML CODE:
<table>
<thead><tr><th>i</th></tr></thead>
<tbody><tr><td class="enabled">0</td></tr>
<tr><td class="enabled">1</td></tr>
</tbody>
</table>
and add manipulate via javascript:
var a = document.getElementsByClassName('enabled');
for (var i = 0; i<a.length;i++) {
if (a[i].textContent == 1) {
a[i].innerHTML = '<label class="label label-success">Online</label>';
}
else {
a[i].innerHTML = '<label class="label label-error">Offline</label>';
}
}
DEMO

Related

ASP.NET MVC Add chebox filtering

I have a table of orders,
filtering, sorting and records per page is done via server side.
How can i make the filtering of the status with the checkbox (see attached screenshot) work?
When changing entries number or searching in searchbox or sorting the action that retrieve the data is triggered (GetList()) , i want to trigger it when check\Uncheck one of the checkbox status.
My Action :
public ActionResult GetList()
{
//Server Side parameters
int start = Convert.ToInt32(Request.Form["start"].FirstOrDefault());
int length = Convert.ToInt32(Request.Form["length"].FirstOrDefault());
string searchValue = Request.Form["search[value]"].FirstOrDefault();
string sortColumnName = Request.Form["columns["+Request.Form["order[0][column]"]+"][name]"].FirstOrDefault();
string sortDirection = Request.Form["order[0][dir]"].FirstOrDefault();
List<Order> orderList = new List<Order>();
orderList = _unitOfWork.Order.GetAll().ToList();
int totalRows = orderList.Count;
foreach (Order order in orderList)
{
order.StringDate = order.UsDate.Day + "/" + order.UsDate.Month + "/" + order.UsDate.Year;
}
//
//filtering done here
//
int totalRowsAfterFiltering = orderList.Count;
//
//Sorting done here
//
//orderList = orderList.OrderBy(x => x.Id //sortColumnName + " " + sortDirection).ToList<Order>();
orderList = orderList.Skip(start).Take(length).ToList<Order>();
foreach (Order order in orderList)
{
order.AllowComplaint = allowComplaint(order.Id.ToString());
}
return Json(new { data = orderList, draw = Request.Form["draw"], recordsTotal = totalRows ,
recordsFiltered = totalRowsAfterFiltering});
}
Javascript\Ajax call the Action :
<script>
$(document).ready(function () {
$('#tblData').DataTable({
"ajax": {
"url": "OrderAdmin/GetList",
"type": "POST",
"datatype": "json"
},
"columns": [
{ "data": "id", "name": "Id" },
{ "data": "orderStatus", "name": "OrderStatus" },
{ "data": "productName", "name": "ProductName" },
{ "data": "stringDate", "name": "StringDate" },
{ "data": "userNameToShow", "name": "UserNameToShow" },
{ "data": "storeName", "name": "StoreName" },
{
"data": "quantity", "name": "Quantity", "render": function (data) {
if (data > 1)
return `<div class="text-center" style="font-weight:bold;background-color:darkseagreen"><label >${data}</label></div>`
else
return `<div class="text-center"><label>${data}</label></div>`
}
},
{ "data": "cost", "name": "Cost" },
{
"data": "fullAddress", "name": "FullAddress", "render": function (data) {
return `<textarea readonly>${data}</textarea>`
},
"width": "20%"
},
{ "data": "trackingNumber", "name": "TrackingNumber", "width": "200px"},
{
"data": {
"orderStatus": "orderStatus",
"id": "id",
"allowComplaint": "allowComplaint"
},
"render": function (data) {
if (data.orderStatus == 'Accepted') {
return `
<div class="text-center">
<a href="/Admin/OrderAdmin/UpdateOrder/${data.id}" class="btn btn-success text-white" style="cursor:pointer">
<i class="fas fa-edit"></i>
</a>
</div>
`}
else if (data.orderStatus == 'Done' && data.allowComplaint) {
return `
<div class="text-center">
<a href="/Admin/Complaints/AddComplaint/${data.id}" class="btn btn-info text-white" style="cursor:pointer">
<i class="fas fa-ticket-alt"></i>
</a>
</div>
`
}
else { return `<div></div>` }
}, "width": "5%"
}
],
"serverSide": "true",
"order": [0, "desc"],
"processing": "true"
});
});
</script>

DataTables add tag to column based on another attribute's value

I am trying to get the <span> tag into the "salesStatusName" column cell that already has some data in it. The tag should be placed in there when the value of the last column "completelyDelivered" is true. However, I also don't want "completelyDelivered" to even be a column in the table, so I assume I somehow need to access the value of "completelyDelivered" attribute in the received JSON.
How it looks now:
https://i.imgur.com/S171i2o.png circle in a separate column
How I want it to look:
https://i.imgur.com/74nCnGu.png circle within Status Name column
I looked around and there are very similar questions, but I was unable to implement any solution.
DataTables instantiation code:
Note that I use AJAX and get JSON code returned
$(document).ready(function () {
$.fn.dataTable.moment('MM-DD-YYYY');
var datatableObj = $('#salesOrdersTable').DataTable({
"ajax": {
"url": "/Orders/GetAll",
"type": "GET",
error: function (error) {
RedirectUserToErrorPage();
}
},
"columns": [
{ "data": "salesOrderNumber" },
{ "data": "salesOrderNumber" },
{ "data": "poNumber" },
{ "data": "orderDateString" },
{ "data": "company" },
{ "data": "salesPerson" },
{ "data": "salesStatusName" },
{ "data": "completelyDelivered" }
],
"columnDefs": [
{
"targets": 0, //salesOrderNumber col
"orderable": false,
"render": function (data) {
return '<input type="button" value="+" onclick="location.href=\'/Shipments/Get?salesOrderNumber=' + data + '\'">';
}
},
{
"targets": 7, //completelyDelivered col
"render": function (data) {
if (String(data) == "true") {
return '<span class="SalesOrderDelivered">⬤</span>';
}
return "";
}
},
{ className: "salesOrderNumber", "targets": 1 },
],
});
I've done some research and figured it out.
Basically, if you write { "data": null }, as a definition for a column, you gain access to all properties of that row. So, in "render": function(data) function, write data["propertyName"] to get the value.
Code:
$(document).ready(function () {
$.fn.dataTable.moment('MM-DD-YYYY');
var datatableObj = $('#salesOrdersTable').DataTable({
"ajax": {
"url": "/Orders/GetAll",
"type": "GET",
error: function (error) {
RedirectUserToErrorPage();
}
},
{"data": "salesOrderNumber",},
{ "data": "salesOrderNumber" },
{ "data": "poNumber" },
{ "data": "orderDateString" },
{ "data": "company" },
{ "data": "salesPerson" },
{ "data": null, },//this is Sales Status column.
//"data: null" accesses all JSON data. We need this so that in "columnDefs" section
//we can use the values of both "completelyDelivered" and "salesStatusName" properties.
],
"columnDefs": [
{
"targets": 0, //button col
"orderable": false,
"render": function (data) {
return '<input type="button" value="+" onclick="location.href=\'/Shipments/GetShipments?salesOrderNumber=' + data + '\'">';
}
},
{
"targets": 6, //Sales Status col.
"render": function (data) { //This is where we can use values of "completelyDelivered" and "salesStatusName" JSON properties.
if (String(data["completelyDelivered"]) == "true") {
return (String(data["salesStatusName"]) + '<span class="AllDelivered"> ⬤</span>');
} else {
return String(data["salesStatusName"]);
}
}
},
{ className: "salesOrderNumber", "targets": 1 },
],
});

Rails and DataTable how to pass the JSON Document

Sorry for the bad title. I am new to Rails and Javascript. I setup a DataTable using child rows following the DataTables documentation using a single ajax call to a JSON file.
I got that all working I now want to use my Rails controller to get the JSON from a Mongo DB. I also have that part working. What I am confused about is probably very simple and I am used to building a Rails table with active record BUT here I had a separate javascript called tests.js with my DataTable definition and the ajax call to a file. Can I now just pass in the JSON from the View somehow? I am not sure how to switch from the ajax call to using the JSON I now have from my controller
$(document).ready(function() {
var table = $('#queryone_table').DataTable( {
"ajax": "/objects.txt",
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "transactionType" },
{ "data": "collationId" },
{ "data": "licensePlate" },
{ "data": "description" },
{ "data": "startDate" },
{ "data": "FeedComplete" },
{ "data": "RepoComplete" },
{ "data": "feedProcessingDuration" },
{ "data": "completeDuration" }
],
"order": [[1, 'asc']]
} );
Objects.txt I would now like to be a var from my View? With active record and MySQL I would build the table in the view looping over a dataset from controller but with the child row code already done in javascript I would like to leave that.
full javascript code
$(document).ready(function() {
var table = $('#queryone_table').DataTable( {
"ajax": "/objects.txt",
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "transactionType" },
{ "data": "collationId" },
{ "data": "licensePlate" },
{ "data": "description" },
{ "data": "startDate" },
{ "data": "FeedComplete" },
{ "data": "RepoComplete" },
{ "data": "feedProcessingDuration" },
{ "data": "completeDuration" }
],
"order": [[1, 'asc']]
} );
// Add event listener for opening and closing details
$('#queryone_table tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row( tr );
if ( row.child.isShown() ) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
row.child( format(row.data()) ).show();
tr.addClass('shown');
}
} );
} );
function format ( d ) {
var foo = '<table id="queryinner_table" cellpadding="5" cellspacing="2" border="1" style="padding-left:50px;" class="table table-striped table-bordered table-hover table-condensed dataTable no-footer sub-table">';
// loop over table rows
var trow = "";
for (var i=0; i< d.nextrow.length; i++) {
var foo2 = '<tr>'+
'<td>Transaction Step:</td>'+
'<td>'+d.nextrow[i].transactionStep+'</td>'+
'<td>'+d.nextrow[i].elapsedSeconds+'</td>'+
'</tr>'
trow = trow + foo2
} //for loop
var foo2 = '</table>';
var res = foo.concat(trow);
res = res.concat(foo2);
return res;
}
This was poorly worded I have started a new project and will ask a few questions based on that code rather than rewrite this one.

How to change an icon in a JQuery Datatables TD element, according to another TD element?

I want to create a Datatable with the JQuery Datatable library, but for beautification and UI reasons, I want an icon to change according to another input field. Lets say,
If td.field 4 is null then td.field 5 icon=1 else icon=2.
You are not going to add an Icon you are going to add a CSS Class and in the CSS class you are going to add the image you want.
Assuming you have made you ajax call and you have the JSON and you are creating the datatable.
table = $('#table').DataTable( {
"columns": [
{ "className":'userName col-md-2', "data": "userName" },
{ "className":'desc col-md-2', "data": "desc" },
{ "className":'timeStart col-md-2', "data": "timeStart" },
{ "className":'timeEnd col-md-2', "data": "timeEnd" },
{ "className":'dispatcher col-md-2', "data": "dispatcher" },
{
"className": 'edit',
"orderable": false,
"data": null,
"defaultContent": ''
},
],
"order": [[2, 'desc']], !NOT FINISHED YET
Immediate after this and before the table.row.add you have to create seperately the createdRow with the Icon you want to manipulate.
Inside the table section you add the statement you want to make for the createdRow.
"createdRow": function ( row, data, index ) {
if ( data.dispatcher == null ) {
$('td', row).eq(5).addClass("edit-incident2");
}else{
$('td', row).eq(5).addClass("edit-incident");
}
}
After this your code would look like the below witch is the fully table code.
table = $('#table ').DataTable( {
"columns": [
{ "className":'userName col-md-2', "data": "userName" },
{ "className":'desc col-md-2', "data": "desc" },
{ "className":'timeStart col-md-2', "data": "timeStart" },
{ "className":'timeEnd col-md-2', "data": "timeEnd" },
{ "className":'dispatcher col-md-2', "data": "dispatcher" },
{
"className": 'edit',
"orderable": false,
"data": null,
"defaultContent": ''
},
],
"order": [[2, 'desc']],
"createdRow": function ( row, data, index ) {
if ( data.dispatcher == null ) {
//console.log(data.dispatcher);
$('td', row).eq(5).addClass("edit-incident2");
}else{
$('td', row).eq(5).addClass("edit-incident");
}
}
} );
Then you draw your table and the statement makes the job.
table.row.add( {
"userName": responsejson.userName,
"desc": responsejson.desc,
"timeStart": responsejson.timeStart,
"timeEnd": responsejson.timeEnd,
"dispatcher": responsejson.dispatcher,
"_id": responsejson._id,
} ).draw();
The two CSS classes would look like this
td.edit-incident {
background: url('../img/incident_management.png') no-repeat center center;
cursor: pointer;}
td.edit-incident2 {
background: url('../img/incident_management2.png') no-repeat center center;
cursor: pointer;}
It is not something incredible fantastic but it took me some hours, and I think the result is nice and very easy for the user to immediately understand what is he looking.
"columns": [
{
"className": 'details-control', "orderable": false, "data": null,"defaultContent": '', "render": function (data, type, row) {
if(data.id==1)
return '<span class="glyphicon glyphicon-remove"></span>';
else
return '<span class="glyphicon glyphicon-ok"></span>';
},
}
]
just modify the column value before render.it's also possible to directly add the icon into datatable with the help of above code
giv ids for each row and tds
<tr id="1">
<td id="1"></td>
<td id="2"></td>
<td id="3"></td>
</tr>
if you creating <td> dynamically using the database
for(i=0;i<upto number of tds in a row;i++)
{
if($('#'+i).text()!='')//find td is null or not
{
$('#'+i).append('if');
}
else
{
$('#'+i).append('else');
}
}

Datatable row grouping

I have a working datatable that is retrieving data from a file :
I want to group row, something like this :
https://datatables.net/examples/advanced_init/row_grouping.html
My goal would to have my datatable to look like this, grouping row by the date (last column), but even looking at the code, I have trouble to make it work. I'd like some help to make that work if you could.
Here is the code of my datatable :
$(document).ready(function() {
$('#datatable').DataTable( {
"ajax": "<?php echo base_url()."assets/files/data/data.txt"; ?>" ,
"columns": [
{ "data": "etat" },
{ "data": "dest" },
{ "data": "message" },
{ "data": "exp" },
{ "data": "date" }
],
"order": [[ 0, "desc" ]],
"responsive": true
} );
} );
You should use drawCallback function.
Try.
$(document).ready(function() {
$('#datatable').DataTable({
"columns": [
{ "data": "etat" },
{ "data": "dest" },
{ "data": "message" },
{ "data": "exp" },
{ "data": "date" },
{ "data": "extra" }
],
"order": [[ 4, "desc" ]],
"responsive": true,
drawCallback: function (settings) {
var api = this.api();
var rows = api.rows({ page: 'current' }).nodes();
var last = null;
api.column(4, { page: 'current' }).data().each(function (group, i) {
if (last !== group) {
$(rows).eq(i).before(
'<tr class="group"><td colspan="8" style="BACKGROUND-COLOR:rgb(237, 208, 0);font-weight:700;color:#006232;">' + 'GRUPO ....' + group + '</td></tr>'
);
last = group;
}
});
}
});
} );
Result: https://jsfiddle.net/cmedina/7kfmyw6x/13/
It seems you get the error when outputting the url by PHP into the Javascript.
Try this instead:
ajax: "<?php echo base_url() . 'assets/files/data/data.txt'; ?>"
Not the single-qoutes in the PHP-code.

Categories