How to copy data of html formatted cell instead of markup - javascript

I have some cells in Handsontable, that are displayed using "html" renderer. When I copy these cells and paste them in Excel, I get html content instead of data. Is there a way to display cells as they are, and get their value when copying ?
JSFiddle example:
example
document.addEventListener("DOMContentLoaded", function() {
var
data = [
{
title: "Title 1",
description: "<div style='text-align:right'>148</div>"
},
{
title: "Title 2",
description: "<div style='text-align:right'>2002</div>"
}
],
container1,
hot1;
container1 = document.getElementById('example1');
hot1 = new Handsontable(container1, {
data: data,
colWidths: [200, 200],
colHeaders: ["Title", "Description"],
columns: [
{data: "title", renderer: "html"},
{data: "description", renderer: "html"}
]
});
});

You can try converting your input data into json format and have a custom renderer which displays the value from json. Add a toString property to the data which will return exactly what you want to get copied.
Here is an updated fiddle: http://jsfiddle.net/mpusarla/gng4wqzy/6/
document.addEventListener("DOMContentLoaded", function() {
var item1 = {};
item1.title = "Title 1 ";
item1.description = {};
item1.description.text = "Desc 1";
item1.description.toString = function() {
return 'Updated Desc for 1';
}
var item2 = {};
item2.title = "Title 2";
item2.description = {};
item2.description.text = "Desc 2";
item2.description.toString = function() {
return 'Updated Desc for 2 ';
}
var data = [];
data.push(item1);
data.push(item2);
var container1, hot1;
function customRenderer(instance, td, row, col, prop, value, cellProperties) {
td.innerHTML = '<div style="text-align:right">' + value.text;
}
container1 = document.getElementById('example1');
hot1 = new Handsontable(container1, {
data: data,
colWidths: [200, 200],
colHeaders: ["Title", "Description"],
columns: [{
data: "title",
renderer: "text"
}, {
data: "description",
renderer: customRenderer
}]
});
});
</style><!-- Ugly Hack due to jsFiddle issue --> <script src="http://docs.handsontable.com/0.15.0/scripts/jquery.min.js"></script> <script src="http://docs.handsontable.com/0.15.0/bower_components/handsontable/dist/handsontable.full.js"></script> <link type="text/css" rel="stylesheet" href="http://docs.handsontable.com/0.15.0/bower_components/handsontable/dist/handsontable.full.min.css">
<div id="example1" class="hot handsontable"></div>

Related

How to add one more column in jquery datatable which is not present in the json response

I'm using one api in which the response is coming in two columns but in one column there are many parameters, I need to decode one column and want to show in different columns.
Column name coming from api timestamp, dataFrame, I need to show in 3 columns timestamp, oil temperature and winding temperature. I need to add one more column in datatable to show the values in the datatable.
sample json data
[{
"timestamp": "2018-07-21T07:56:23.838Z",
"dataFrame": "HA=="
},
{
"timestamp": "2018-07-21T08:16:23.902Z",
"dataFrame": "HA=="
}
]
output
Expected Output
Timestamp, Oil Temp, winding temp in 3 separate columns
code
<script>
window.onload = getddata();
function getddata() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var Readings = JSON.parse(xmlhttp.responseText);
//jquery data table - start
$(document).ready(function () {
$('#example').DataTable({
columnDefs: [{
"targets": 1,
"render": function (data, type, row, meta) {
var hexvalue =base64toHEX(data);
var deviceid= hexToDec(hexvalue.substr(1,1));
var oil_temp= hexToDec(hexvalue.substr(2,2));
var winding_temp= hexToDec(hexvalue.substr(4,2));
return 'oil temp: ' + oil_temp + ', Winding Temp: ' + winding_temp + ' ;
}
},
{
"targets": 0,
"render": function (data, type, row, meta) {
var updDate= UtcToIst(data).toLocaleDateString();
var updTime= UtcToIst(data).toLocaleTimeString();
var updDateTime=updDate + ", " + updTime;
return updDateTime ;
}
}
}
],
data: Readings,
columns: [{
"data": "timestamp"
}, {
"data": "dataFrame"
}
]
});
});
//data table code -close
}
};
xmlhttp.open("GET", "https://.., true);
xmlhttp.setRequestHeader("Authorization", "Basic a2VybmV");
xmlhttp.setRequestHeader("Content-type", "Application/json");
xmlhttp.send();
}
</script>
It seems to me the code is a little bit overcomplicated. Why not just reuse dataFrame over multiple columns? Perhaps I misunderstand the question ...
var table = $('#example').DataTable({
data: sampleReadings,
columns: [
{ data: 'timestamp', title: 'timestamp',
render: function(data) {
return data
/* dont know what UtcToIst is
var updDate= UtcToIst(data).toLocaleDateString();
var updTime= UtcToIst(data).toLocaleTimeString();
var updDateTime=updDate + ", " + updTime;
return updDateTime ;
*/
}
},
{ data: 'dataFrame', title: 'deviceid',
render: function(data) {
var hexvalue = base64toHEX(data);
return hexToDec(hexvalue.substr(1,1));
}
},
{ data: 'dataFrame', title: 'Oil temp',
render: function(data) {
var hexvalue = base64toHEX(data);
return hexToDec(hexvalue.substr(2,2));
}
},
{ data: 'dataFrame', title: 'Winding temp',
render: function(data) {
var hexvalue = base64toHEX(data);
return hexToDec(hexvalue.substr(4,2));
}
},
//I guess there is more data hidden in dataFrame
//You can almost copy paste new columns here
]
})
If you have 10.000 records it would be a good idea to cache the output from base64toHEX.
demo -> http://jsfiddle.net/fn0yL361/
You can simply add a new column and render related value. Please update the data tables column.
https://datatables.net/reference/option/columns.name
{ columnDefs: [{
"targets": 2,
"name": "winding temp",
"render": function (data, type, row, meta) {
var hexvalue =base64toHEX(data);
var deviceid= hexToDec(hexvalue.substr(1,1));
var oil_temp= hexToDec(hexvalue.substr(2,2));
var winding_temp= hexToDec(hexvalue.substr(4,2));
return 'Winding Temp: ' + winding_temp ;
}
},{
"targets": 1,
"name": "Oil temp",
"render": function (data, type, row, meta) {
var hexvalue =base64toHEX(data);
var deviceid= hexToDec(hexvalue.substr(1,1));
var oil_temp= hexToDec(hexvalue.substr(2,2));
var winding_temp= hexToDec(hexvalue.substr(4,2));
return 'oil temp: ' + oil_temp ;
}
},
{
"targets": 0,
"name" : "Timestamp",
"render": function (data, type, row, meta) {
var updDate= UtcToIst(data).toLocaleDateString();
var updTime= UtcToIst(data).toLocaleTimeString();
var updDateTime=updDate + ", " + updTime;
return updDateTime ;
}
}
],
data: Readings,
columns: [{
"data": "timestamp"
}, {
"data": "dataFrame"
},
{
"data": "dataFrame"
}
]
Here is an example, because there are spaces in Name so need some extra code to get field:
var str = "{timestamp: 'xxx', dataFrame: 'Old Time: xx, winding Time: yyyy, Ambient Time: zzzz'}";
var objOrg = JSON.parse(str);
var newJSon = [{}];
foreach (var itm in objOrg)
{
var new3Fields = itm.dataFrame;
var arr = new3Fields.split(',')
var newItem = {};
newItem.timestamp = itm.timestamp;
newItem.OldTime = JSON.parse(arr[0]).['Old Time'];
newItem.WindingTime = JSON.parse(arr[1]).['winding Time'];
newItem.AmbientTime = JSON.parse(arr[2]).['Ambient Time'];
newJSon += newItem;
}
newJSon <--- This is a list with 4 columns

jQuery datatable - unexpected vertical scrollbar

I am trying display data in jQuery datatable but, I am seeing unexpected vertical scrollbar.
Fiddler: https://jsfiddle.net/8f63kmeo/15/
HTML:
<table id="CustomFilterOnTop" class="table table-bordered table-condensed" width="100%"></table>
JS
var Report4Component = (function () {
function Report4Component() {
//contorls
this.customFilterOnTopControl = "CustomFilterOnTop"; //table id
//data table object
this.customFilterOnTopGrid = null;
//variables
this.result = null;
}
Report4Component.prototype.ShowGrid = function () {
var instance = this;
//create the datatable object
instance.customFilterOnTopGrid = $('#' + instance.customFilterOnTopControl).DataTable({
columns: [
{ title: "<input name='SelectOrDeselect' value='1' id='ChkBoxSelectAllOrDeselect' type='checkbox'/>" },
{ data: "Description", title: "Desc" },
{ data: "Status", title: "Status" },
{ data: "Count", title: "Count" }
],
"paging": true,
scrollCollapse: true,
"scrollX": true,
scrollY: "50vh",
deferRender: true,
scroller: true,
dom: '<"top"Bf<"clear">>rt <"bottom"<"Notes">i<"clear">>',
buttons: [
{
text: 'Load All',
action: function (e, dt, node, config) {
instance.ShowData(10000);
}
}
],
columnDefs: [{
orderable: false,
className: 'select-checkbox text-center',
targets: 0,
render: function (data, type, row) {
return '';
}
}],
select: {
style: 'multi',
selector: 'td:first-child',
className: 'selected-row selected'
}
});
};
Report4Component.prototype.ShowData = function (limit) {
if (limit === void 0) { limit = 2; }
var instance = this;
instance.customFilterOnTopGrid.clear(); //latest api function
instance.result = instance.GetData(limit);
instance.customFilterOnTopGrid.rows.add(instance.result.RecordList);
instance.customFilterOnTopGrid.draw();
};
Report4Component.prototype.GetData = function (limit) {
//structure of the response from controller method
var resultObj = {};
resultObj.Total = 0;
resultObj.RecordList = [];
for (var i = 1; i <= limit; i++) {
resultObj.Total += i;
var record = {};
record.Description = "Some test data will be displayed here.This is a test description of record " + i;
record.Status = ["A", "B", "C", "D"][Math.floor(Math.random() * 4)] + 'name text ' + i;
record.Count = i;
resultObj.RecordList.push(record);
}
return resultObj;
};
return Report4Component;
}());
$(function () {
var report4Component = new Report4Component();
report4Component.ShowGrid();
report4Component.ShowData();
});
function StopPropagation(evt) {
if (evt.stopPropagation !== undefined) {
evt.stopPropagation();
}
else {
evt.cancelBubble = true;
}
}
ISSUE:
I am wondering why the vertical scrollbar is appearing and why I am seeing an incorrect count...? Is it because my datatable has rows with multiple lines? As I have already set the scrolly to 50vh, I am expecting all the rows to be displayed.
Note:
The table should support large data too. I have enabled scroller for that purpose as it is required as per the application design. To verify that click on "Load all" button.
Any suggestion / help will be greatly appreciated?
You just need to remove property " scroller: true" it will solve your problem.
For demo please check https://jsfiddle.net/dipakthoke07/8f63kmeo/20/

Passing data into chart using HTML and JavaScript

The following code is used to display a chart. The problem is the "data" is hard coded in. How can I change this so that the chart displays values which are displayed using:
<div id="name"> </div>
<div id="testscore"></div>
The above 2 div's contain dynamic values. I want to display these values in the chart.
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer",
{
// title:{
// text: "Olympic Medals of all Times (till 2012 Olympics)"
// },
animationEnabled: true,
legend: {
cursor:"pointer",
itemclick : function(e) {
if (typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
e.dataSeries.visible = false;
}
else {
e.dataSeries.visible = true;
}
chart.render();
}
},
axisY: {
title: "Time"
},
toolTip: {
shared: true,
content: function(e){
var str = '';
var total = 0 ;
var str3;
var str2 ;
for (var i = 0; i < e.entries.length; i++){
var str1 = "<span style= 'color:"+e.entries[i].dataSeries.color + "'> " + e.entries[i].dataSeries.name + "</span>: <strong>"+ e.entries[i].dataPoint.y + "</strong> <br/>" ;
total = e.entries[i].dataPoint.y + total;
str = str.concat(str1);
}
str2 = "<span style = 'color:DodgerBlue; '><strong>"+e.entries[0].dataPoint.label + "</strong></span><br/>";
str3 = "<span style = 'color:Tomato '>Total: </span><strong>" + total + "</strong><br/>";
return (str2.concat(str)).concat(str3);
}
},
data: [
{
type: "bar",
showInLegend: true,
name: "Black",
color: "#000000",
dataPoints: [
{ y: 0.18, label: "Name"},
{ y: 0.12, label: "Name 1"},
{ y: 0.59, label: "Name 2"},
{ y: 1.15, label: "Name 3"},
]
},
]
});
chart.render();
}
</script>
You can simply call
var data = document.getElementById('name').value;
var data2 = document.getElementById('testscore').value;
If it's a single value, it would work; otherwise, you need to do it this way:
var array = $('#your.id').data('stuff');
Here, "stuff" is nothing but
<div data-stuff="some data" ></div>
Or, create an array by:
var array = new Array();
and finally, store the data into the array.

How to create custom dropdownlist in kendo grid header column?

Actually my requirement is want to create custom dropdownlist in the column header of kendo grid. I don't down like nrwant to use filtler column. I just want to add normal dropdown in header. Please provide any example like that so that i can move forward on my task.
Thanks in advance...
In your column definition add a property like this:
headerTemplate: '<input id="dropdown" />'
Then after your grid initialization do:
$("#dropdown").kendoDropDownList({...init parameters...});
UPDATE: go to dojo.telerik.com and paste in the following code:
<div id="grid"></div>
<script>
$("#grid").kendoGrid({
columns: [
{
field: "ProductName",
title: "Product Name",
headerTemplate: '<input id="dropdown" />'
},
{ field: "UnitPrice", title: "Price", template: 'Price: #: kendo.format("{0:c}", UnitPrice)#' }
],
pageable: true,
dataSource: {
transport: {
read: {
url: "http://demos.telerik.com/kendo-ui/service/products",
dataType: "jsonp"
}
},
pageSize: 10
},
excelExport: function(e) {
var sheet = e.workbook.sheets[0];
var template = kendo.template(this.columns[1].template);
for (var i = 1; i < sheet.rows.length; i++) {
var row = sheet.rows[i];
var dataItem = {
UnitPrice: row.cells[1].value
};
row.cells[1].value = template(dataItem);
}
}
});
$("#dropdown").kendoDropDownList({
optionLabel: 'Choose a value...',
dataTextField: 'description',
dataValueField: 'id',
dataSource:{
data: [{id: 1, description: 'One'},{id: 2, description: 'Two'}]
},
change: function(e){
//do whatever you need here, for example:
var theGrid = $("#grid").getKendoGrid();
var theData = theGrid.dataSource.data();
$(theData).each(function(index,item){
item.ProductName = e.sender.text();
});
theGrid.dataSource.data(theData);
}
});

Refreshing grid data on click event

I have this code. In here I am retrieving a new set of values via a URL through Jquery Ajax($.get()) on calling a function gotoa() on some click event. I am obtaining the set of values correctly as i am getting right result on alert. But the grid is not updating itself at that moment. When i refresh the whole page then the grid updates. How to update the grid on calling of gotoa() itself. ?
The code ::
<script type="text/javascript">
function gotoa(){
$.get("http://localhost:8080/2_8_2012/jsp/GetJson.jsp?random=" + new Date().getTime(), function(result){
alert(result);
var storedata={
identifier:"ID",
label:"name",
items:result
};
var store = new dojo.data.ItemFileWriteStore({data: storedata});
alert(store);
//var gridh = dijit.byId("gridDiv");
//gridh.setStore(store);
var gridStructure =[[
{ field: "ID",
name: "ID_Emp",
width: "20%",
classes:"firstname"
},
{
field: "Names",
name: "Name",
width: "20%",
classes: "firstname"
},
{ field: "Email",
name: "Mail",
width: "20%",
classes:"firstname"
}
]
];
var grid1 = new dojox.grid.DataGrid({
id: 'grid2',
store: store,
structure: gridStructure,
rowSelector: '30px',
selectionMode: "single",
autoHeight:true,
columnReordering:true},
document.createElement('div'));
/*append the new grid to the div*/
dojo.byId("gridDiv").appendChild(grid1.domNode);
/*Call startup() to render the grid*/
grid1.startup();
// assuming our grid is stored in a variable called "myGrid":
dojo.connect(grid1, "onSelectionChanged", grid1, function(){
var items = grid1.selection.getSelected();
// do something with the selected items
dojo.forEach(items, function(item){
var v = grid1.store.getValue(item, "Names");
function showDialog() {
dojo.require('dijit.Tooltip');
dijit.byId("terms").show();
}
//if(name!="Mail")
showDialog();
}, grid1);
});
dojo.connect(grid1, "onCellClick", grid1, function sendmail(){
var items = grid1.selection.getSelected();
dojo.forEach(items, function(item){
var v1 = grid1.store.getValue(item, "Email");
alert(v1);
request.setAttribute("variablemail", v1);
});
});
},"text");
}
</script>
The output of alert(result) at a particular point of time is like this ::
[{"ID":1,"Names":"Shantanu","Email":"shantanu.tomar#gmail.com"},{"ID":2,"Names":"Mayur","Email":"mayur.sharma#gmail.com"},{"ID":3,"Names":"Rohit"},{"ID":4,"Names":"Jasdeep"},{"ID":5,"Names":"Rakesh","Email":"rakesh.shukla#gmail.com"},{"ID":6,"Names":"Divyanshu"},{"ID":8,"Names":"hello"},{"ID":9,"Names":"fine"},{"ID":10,"Names":"shivani"}]
And the output of alert(store) is like ::
[object Object]
And i am calling gotoa() on clicking anywhere inside a content pane(for the time being, later on will put a button or something) like this ::
<div dojoType="dijit.layout.ContentPane" title="Pending Activities" style="background-image: url('http://localhost:8080/2_8_2012/images/17.png');" onClick="gotoa();">
How to upgrade grid data ? thanks.
I am a newbie to dojo, i think this code will help you::
<script type="text/javascript">
function gotoa(isUpdate){
$.get("http://localhost:8080/2_8_2012/jsp/GetJson.jsp?random=" + new Date().getTime(), function(result){
alert(result);
var storedata={
identifier:"ID",
label:"name",
items:result
};
var store = new dojo.data.ItemFileWriteStore({data: storedata});
alert(store);
if (isUpdate) {
var grid = dojo.byId('grid2');
grid.setStore(store);
} else {
var gridStructure =[[
{ field: "ID",
name: "ID_Emp",
width: "20%",
classes:"firstname"
},
{
field: "Names",
name: "Name",
width: "20%",
classes: "firstname"
},
{ field: "Email",
name: "Mail",
width: "20%",
classes:"firstname"
}
]
];
var grid1 = new dojox.grid.DataGrid({
id: 'grid2',
store: store,
structure: gridStructure,
rowSelector: '30px',
selectionMode: "single",
autoHeight:true,
columnReordering:true},
document.createElement('div'));
/*append the new grid to the div*/
dojo.byId("gridDiv").appendChild(grid1.domNode);
/*Call startup() to render the grid*/
grid1.startup();
// assuming our grid is stored in a variable called "myGrid":
dojo.connect(grid1, "onSelectionChanged", grid1, function(){
var items = grid1.selection.getSelected();
// do something with the selected items
dojo.forEach(items, function(item){
var v = grid1.store.getValue(item, "Names");
function showDialog() {
dojo.require('dijit.Tooltip');
dijit.byId("terms").show();
}
//if(name!="Mail")
showDialog();
}, grid1);
});
dojo.connect(grid1, "onCellClick", grid1, function sendmail(){
var items = grid1.selection.getSelected();
dojo.forEach(items, function(item){
var v1 = grid1.store.getValue(item, "Email");
alert(v1);
request.setAttribute("variablemail", v1);
});
});
}
});
}
</script>
use gotoa() for initial loading of grid and gotoa(true) for updating the grid.

Categories