Datatable fnCellRender doesn't render - javascript

I am trying to render some fields before exporting to excel in my function I am doing like this;
"tableTools": {
"sSwfPath": "assets/global/plugins/data-tables/tabletools/swf/copy_csv_xls_pdf.swf",
"aButtons": [ {
"sExtends": "xls",
"sButtonText": "Excel",
"fnCellRender":function(sValue,iColumn,nTr,iDataIndex){
console.log(sValue);
//console.log($(sValue));
return sValue;
}
}, {
"sExtends": "print",
"sButtonText": lang.L_PRINT,
"sInfo": lang.L_PRINT_DESC,
"sMessage": "Metrics"
}]
}
So when I uncomment
console.log($(sValue));
it returns just first and second column which doesn't include any html tag inside. But when it finds a value that have html tag it stops.
ex - this gets the valu
<td class=" sorting_1">201408</td>
this doesn't
<span style="text-align:right;display:block;width:100%">121.25</span>
How can I fix it ?

To troubleshoot this I found it much easier to just write the data into the CSV and see the format so I could then choose how to parse.
When you use the fnCellRender property TableTools will not do any parsing of the HTML anymore. I would expect that you would see the raw data in the console window some of which would be HTML I assume and others just values.
When it's HTML you can use JQuery to extract the values or a regular expression. E.g
if ($(sValue).prop("checked")) {
return "TRUE";
} else {
return "FALSE";
}
or in your case
return $(sValue).val();
Some research I used:
TableTools background and good discussion with links
TableTools Reference API

Related

Formatting server side jQuery Datatable

I am trying to format the front end look of my jQuery DataTable
I currently have it looking like this https://imgur.com/a/PPgL48Y
I need the repeating items in each row to be remove for example in the first row there are 2 Owner 1's. I only want to display a single Owner 1 in that row.
The other issue is in row 2, Url1 is followed by a comma then Url 2 but i want
Url1
Url2
In the row, so removing the comma and adding a new line in that col
My data is being collected via server side processing
My current jQuery code
<script type="text/javascript" >
$('#result').DataTable({
"serverSide":true,
"filter": false,
"orderMulti": false,
"ajax": "DetailedSearch?handler=ServerSideDataTable",
"columns":[
{"data": "location",
"render": function(data,type,row){
return row.location;
}
},
{"data": "contactAndRole",
"render": function(data,type,row){
return data.key + " - " + data.value;
}},
{"data": "server", "sortable": "false"},
{"data": "urls",
"render": function(data,type,row){
return row.urls + '<br>';
}
}
],
rowGroup:{
dataSrc:'appName'
}
});
</script>
Can i add some html elements? like a br after each url, or can the table be constructed with pure html then passed onto data tables to output?
I've looked into the HTML templates, and standalone documentation on the data tables website but nothing seems to be helpful.
The commas for the url's array are because of the default way arrays are processed to strings to be printed into the html in the dom
You could join() them yourself using a <br> separator instead
return row.urls.join('<br/>')

How can I access array element value in json

I'm not able to access _sValues in my html page, however i can able to console.log the interested _sValues array element in console.
JSON
[
{
"_this":{
"_isEvent":false,
"_sNames":[
"name",
"tag",
"notes",
"input",
"type",
"action"
],
"_sValues":[
"Testing01",
"#13",
"1504013826",
"No details",
"cType",
"NA"
],
"_cName":"namesList",
"_dName":"TEST",
"_id":"12345",
}
}
]
HTML
<th class="col-md-5 col-xs-5" data-field="_this._sValues[1]" data-sortable="true">S-VALUES</th>
I would like to see #13 displayed on the page instead i don't see any values or console error. However i can display all values by doing _this.sValues
SCRIPT
var data;
$(function () {
$.getJSON("http://localhost:8080/services/webapi/getAllData", function(json){
data = json;
$('#table').bootstrapTable({
data: data
});
});
});
DEV TOOL
data[0]._this._sValues[1]
"#13"
In your case,
i assume you only have one row.
$(".col-md-5").attr("data-field",data[0]._this._sValues[1]);
It will inject the data to html.
If you have multi row, you can use for loop.
I believe you have a silent error. It has to do with the trailing comma in your data object.
"_id":"12345",
// should be
"_id":"12345"
That's all I noticed. I Courbet wrong but I know trailing commas mess with some browsers.

How to use function in Kendo Grid Column Template with AngularJS

I have a column in a Kendo grid that I want to perform some specific logic for when rendering, and am using Angular. I have the grid columns set up using the k-columns directive.
After looking at the documentation, it seemed simple: I could add the template option to my column, define the function to perform my logic, and pass the dataItem value in. What I have looks something like this:
k-columns='[{ field: "Name", title: "Name",
template: function (dataItem){
// Perform logic on value with dataItem.Name
// Return a string
}
}]'
However, running this causes a syntax error complaining about the character '{' that forms the opening of the block in my function.
I have seen several examples of defining a template function in this format. Is there something else that needs to be done for this to work? Am I doing something incorrectly? Is there another way of defining the template as a function and passing the column data to it? (I tried making a function on my $scope, which worked, except I couldn't figure out how to get data passed into the function.)
Thank you for your help.
It appears that defining a column template in this fashion isn't supported when using AngularJS and Kendo. This approach works for projects that do not use Angular (standard MVVM), but fails with its inclusion.
The workaround that a colleague of mine discovered is to build the template using ng-bind to specify a templating function on the $scope, all inside of a span:
template: "<span ng-bind=templateFunction(dataItem.Name)>#: data.Name# </span>"
This is the default column templating approach that is implemented by Telerik in their Kendo-Angular source code. I don't know yet if the data.Name value is required or not, but this works for us.
Warning: Don't have access to Kendo to test the code at the moment, but this should be very close
In your case, you are assigning a a string to the value of k-columns and that string contains the the word function and your curly brace {
You need to make sure the function gets executed ... something like this:
k-columns=[
{
field: "Name",
title: "Name",
template: (function (dataItem){
// Perform logic on value with dataItem.Name
// Return a string
}())
}
];
Note the difference:
We create an object -- a real honest-to-goodness object, and we use an IIFE to populate the template property.
Maybe, it will be useful for someone - this code works for me too:
columns: [
{
field: "processed",
title:"Processed",
width: "100px",
template: '<input type="checkbox" ng-model="dataItem.processed" />'
},
and you get the two-way binding with something like this:
<div class="col-md-2">
<label class="checkbox-inline">
<input type="checkbox" ng-model="vm.selectedInvoice.processed">
processed
</label>
</div>
This can be done via the columns.template parameter by supplying a callback function whose parameter is an object representing the row. If you give the row a field named name, this will be the property of the object you reference:
$("#grid").kendoGrid({
columns: [ {
field: "name",
title: "Name",
template: function(data) {
return data.name + "has my respect."
}
}],
dataSource: [ { name: "Jane Doe" }, { name: "John Doe" } ]
});
More information is available on Kendo's columns.template reference page.
After hours of searching. Here is the conclusion that worked:
access your grid data as {{dataItem.masterNoteId}} and your $scope data as simply the property name or function.
Example
template: '<i class="fa fa-edit"></i>',
I really hope this safes somebody life :)
just use like my example:
}, {
field: "TrackingNumber",
title: "#T("Admin.Orders.Shipments.TrackingNumber")",
//template: '<a class="k-link" href="#Url.Content("~/Admin/Shipment/ShipmentDetails/")#=Id#">#=kendo.htmlEncode(TrackingNumber)#</a>'
}, {
field: "ShippingMethodName",
title: "#T("Admin.Orders.Shipments.ShippingMethodName")",
template:function(dataItem) {
var template;
var ShippingMethodPluginName = dataItem.ShippingMethodPluginName;
var IsReferanceActive = dataItem.IsReferanceActive;
var ShippingMethodName = dataItem.ShippingMethodName;
var CargoReferanceNo = dataItem.CargoReferanceNo;
var ShipmentStatusId = dataItem.ShipmentStatusId;
if (ShipmentStatusId == 7) {
return "<div align='center'><label class='label-control'><b style='color:red'>Sipariş İptal Edildi<b></label></div>";
} else {
if (ShippingMethodPluginName == "Shipping.ArasCargo" || ShippingMethodPluginName == "Shipping.ArasCargoMP") {
template =
"<div align='center'><img src = '/content/images/aras-kargo-logo.png' width = '80' height = '40'/> <label class='label-control'><b>Delopi Aras Kargo Kodu<b></label>";
if (IsReferanceActive) {
template =
template +
"<label class='label-control'><b style='color:red; font-size:20px'>"+CargoReferanceNo+"<b></label></div>";
}
return template;
}

How do I add an index column to Datatable?

I want to add a row number for each row in my data table. I am using plugin from http://datatables.net The page which tells how to add the index is http://datatables.net/release-datatables/examples/api/counter_column.html
... however I don't know how to actually implement it to make it work. I know extremely little about jquery / javascript which would help in this case. I don't know where to put this code to make it work (if it helps i am also using Ruby on Rails)
The initialization code is:
jQuery ->
$('#staffs').dataTable
sPaginationType: "full_numbers"
bJQueryUI: true
}
Here is an example from datatables.net site DataTables row numbers example
$(document).ready(function() {
$('#staffs').dataTable( {
sPaginationType: "full_numbers",
bJQueryUI: true,
"fnDrawCallback": function ( oSettings ) {
/* Need to redo the counters if filtered or sorted */
if ( oSettings.bSorted || oSettings.bFiltered )
{
for ( var i=0, iLen=oSettings.aiDisplay.length ; i<iLen ; i++ )
{
$('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr ).html( i+1 );
}
}
},
"aoColumnDefs": [
{ "bSortable": false, "aTargets": [ 0 ] }
],
"aaSorting": [[ 1, 'asc' ]]
} );
} );
Regarding your SyntaxError: reserved word "function" on line 4 (in /home/ubuntu/ruby/scoreboard/app/assets/javascripts/staffs.js.coffee)' error
take a look at this rails, getting syntax error with coffee script
jquery is javascript. You need to add the code Daniel pasted between
<script language="javascript">
and
</script>
tags.
I am working with latest dataTable 1.10 and gem rails datatable and ajx
for
finding the DataTable row number(Serial Number)
def data
outer = []
records.each_with_index do |record, index|
outer << [
# comma separated list of the values for each cell of a table row
# example: record.attribute,
index + 1 + params[:start].to_i,
record.company_name,
record.id,
record.patients.count,
record.revenue_total
]
end
outer
end

jQuery DataTables - Remove Label

I'm trying to remove the words "Search:" from the filter label in DataTables. I have tried to use jQuery to replace the label dom but when replaced the filter will not work. Any one have any other solutions?
Well seems everybody wants code:
<div id="table-staff_wrapper" class="dataTables_wrapper">
<div id="table-staff_length" class="dataTables_length">
<div id="table-staff_filter" class="dataTables_filter">
<label>
Search:
<input type="text">
</label>
</div>
<table id="table-staff" cellspacing="0" cellpadding="0">
<div id="table-staff_info" class="dataTables_info">Showing 1 to 3 of 3 entries</div>
<div id="table-staff_paginate" class="dataTables_paginate paging_full_numbers">
the above is auto generated by DataTables
refer this link http://datatables.net/ref#sinfo
add this thing to your code--
"oLanguage": { "sSearch": "" }
even if you don't get what you wished then you can simply post the same question on dataTable forum...dataload team will assist you...
Hope it will help you..
You must initialize datatables like this:
$('#yourtable').dataTable({
//your normal options
"oLanguage": { "sSearch": "" }
});
For datatables 1.10.10 (& possibly above), you can use following configuration while creating the datatables instance:
$('.datatable').DataTable({
// other initialization configurations...
// ...
"language": {
"search": "_INPUT_",
"searchPlaceholder": "Search..."
}
});
For more details, here is the link from DataTables site: https://datatables.net/reference/option/language.searchPlaceholder
For Datatables 1.9.4 and above you can use this
$('#yourtable').dataTable({
//your normal options
"language": { "search": "" }
});
Put placeholder when you remove search label
$("#data-table").DataTable({
language: { search: "",searchPlaceholder: "Search..." }
});
try below code:
jQuery("level").html("") or
jQuery("level").text("") or
jQuery("level").get(0).text("")
this will get all the level tag element,
since there is only on ehere use index 0.
It will find level element and set the value as ""
For some reason Placeholder wasn't working for me.
So, My workaround for removing Label and Putting place holder is,
$('#RecentLogs').dataTable({
"oLanguage": { "sSearch": "" }
});
So, above code will remove search label.
And for placeholder.
$('.dataTables_filter input').attr("placeholder", "Search Here");
Note :- Be sure that you are including placehoder's jquery line after datatable's initialization and after loading external js of datatable.

Categories

Resources