updating a CanvasJS Chart from fields on HTML form - html

I've got a simple graph built that I want to update from fields on my HTML form. I can get the graph to render when I put in "hard-coded" numbers - but when I attempt to use variable declarations instead it doesn't work.
I would also like it to re-render the chart onchange...
I know you are all going to just shake your head at the simplicity of this, and I will too probably - AFTER someone enlightens me as to what I'm doing wrong or NOT doing.
Anyway - here is the code for the 3 fields and the graph (You'll notice I've used the variables "q", "c", and "b" under "dataPoints:"):
<!DOCTYPE HTML>
<form>
<label for="QSUMTOT">QSUMTOT entry:</label>
<input id='QSUMTOT' type='text' value='' style='border:1px solid #000000;'/>
<label for="CSUMTOT">CSUMTOT entry:</label>
<input id='CSUMTOT' type='text' value='' style='border:1px solid #000000;'/>
<label for="BSUMTOT">BSUMTOT entry:</label>
<input id='BSUMTOT' type='text' value='' style='border:1px solid #000000;'/>
<div id="chartContainer" style="height: 300px; width: 400px;"></div>
</form>
<script type="text/javascript" src="assets/canvasjs.min.js"></script>
<script type="text/javascript">
window.onload = function () {
var q = document.getElementById("QSUMTOT").value;
var c = document.getElementById("CSUMTOT").value;
var b = document.getElementById("BSUMTOT").value;
var chart = new CanvasJS.Chart("chartContainer", {
title:{
text: "Graphic results of Analysis"
},
data: [//array of dataSeries
{ //dataSeries object
type: "column",
dataPoints: [
{ label: "Quality System", y: q },
{ label: "Compliance", y: c },
{ label: "Business", y: b }
]
}
]
});
chart.render();
}
</script>

Discovered the answer quite by accident:
function summary(){
var qSumTot = document.getElementById("QTOT").value;
var cSumTot = document.getElementById("CTOT").value;
var bSumTot = document.getElementById("BTOT").value;
var q = qSumTot.substring(0, qSumTot.length -1);
var c = cSumTot.substring(0, cSumTot.length -1);
var b = bSumTot.substring(0, bSumTot.length -1);
var analTot = [q * 1, c * 1, b * 1]
var str = document.getElementById('SUMTOT').value;
var rstr = str.substring(0, str.length - 1);
var qms = analTot[0];
var comp = analTot[1];
var bus = analTot[2];
document.getElementById("QSUMTOT").value = qSumTot;
document.getElementById("CSUMTOT").value = cSumTot;
document.getElementById("BSUMTOT").value = bSumTot;
document.getElementById('SUMTOT').value = (parseInt(((q*1) + (c*1) + (b*1))/3) + "%");
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Graph of Analysis"
},
axisY:{
suffix: "%"
},
data: [{
type: "column",
toolTipContent: "{y}%",
dataPoints: [{
label: "QMS",
y: qms
}, {
label: "Compliance",
y: comp
}, {
label: "Business",
y: bus
}]
}]
});
chart.render();
}

Related

Is it possible that we can add dynamic borders to X axis labels and sub labels in chart.js?

I need to create dynamic borders to labels and sub labels of chart.js graph. Is there any way of achieving this scenario?.
Below is the output I am expecting.
Labels and sub labels are having borders
Has anyone been able to achieve this with the library?
Thanks in advance.
I have tried this code but unable to get borders to labels.
var data = [{"omlPartgroupid":"191 ","xmonth":"10","xyear":"2015","QTY":"52"},{"omlPartgroupid":"191 ","xmonth":"11","xyear":"2015","QTY":"145"},{"omlPartgroupid":"191 ","xmonth":"12","xyear":"2015","QTY":"122"},{"omlPartgroupid":"191 ","xmonth":"1","xyear":"2016","QTY":"348"},{"omlPartgroupid":"191 ","xmonth":"2","xyear":"2016","QTY":"460"},{"omlPartgroupid":"191 ","xmonth":"3","xyear":"2016","QTY":"187"},{"omlPartgroupid":"191 ","xmonth":"4","xyear":"2016","QTY":"109"},{"omlPartgroupid":"191 ","xmonth":"5","xyear":"2016","QTY":"234"},{"omlPartgroupid":"191 ","xmonth":"6","xyear":"2016","QTY":"166"},{"omlPartgroupid":"191 ","xmonth":"7","xyear":"2016","QTY":"186"},{"omlPartgroupid":"191 ","xmonth":"8","xyear":"2016","QTY":"250"},{"omlPartgroupid":"191 ","xmonth":"9","xyear":"2016","QTY":"1077"},{"omlPartgroupid":"191 ","xmonth":"10","xyear":"2016","QTY":"594"},{"omlPartgroupid":"193 ","xmonth":"10","xyear":"2015","QTY":"39"},{"omlPartgroupid":"193 ","xmonth":"11","xyear":"2015","QTY":"183"},{"omlPartgroupid":"193 ","xmonth":"12","xyear":"2015","QTY":"136"},{"omlPartgroupid":"193 ","xmonth":"1","xyear":"2016","QTY":"212"},{"omlPartgroupid":"193 ","xmonth":"2","xyear":"2016","QTY":"460"},{"omlPartgroupid":"193 ","xmonth":"3","xyear":"2016","QTY":"176"},{"omlPartgroupid":"193 ","xmonth":"4","xyear":"2016","QTY":"187"},{"omlPartgroupid":"193 ","xmonth":"5","xyear":"2016","QTY":"174"},{"omlPartgroupid":"193 ","xmonth":"6","xyear":"2016","QTY":"151"},{"omlPartgroupid":"193 ","xmonth":"7","xyear":"2016","QTY":"164"},{"omlPartgroupid":"193 ","xmonth":"8","xyear":"2016","QTY":"237"},{"omlPartgroupid":"193 ","xmonth":"9","xyear":"2016","QTY":"798"},{"omlPartgroupid":"193 ","xmonth":"10","xyear":"2016","QTY":"662"},{"omlPartgroupid":"195 ","xmonth":"10","xyear":"2015","QTY":"9"},{"omlPartgroupid":"195 ","xmonth":"11","xyear":"2015","QTY":"38"},{"omlPartgroupid":"195 ","xmonth":"12","xyear":"2015","QTY":"35"},{"omlPartgroupid":"195 ","xmonth":"1","xyear":"2016","QTY":"68"},{"omlPartgroupid":"195 ","xmonth":"2","xyear":"2016","QTY":"161"},{"omlPartgroupid":"195 ","xmonth":"3","xyear":"2016","QTY":"73"},{"omlPartgroupid":"195 ","xmonth":"4","xyear":"2016","QTY":"69"},{"omlPartgroupid":"195 ","xmonth":"5","xyear":"2016","QTY":"56"},{"omlPartgroupid":"195 ","xmonth":"6","xyear":"2016","QTY":"55"},{"omlPartgroupid":"195 ","xmonth":"7","xyear":"2016","QTY":"50"},{"omlPartgroupid":"195 ","xmonth":"8","xyear":"2016","QTY":"114"},{"omlPartgroupid":"195 ","xmonth":"9","xyear":"2016","QTY":"1046"},{"omlPartgroupid":"195 ","xmonth":"10","xyear":"2016","QTY":"883"},{"omlPartgroupid":"197 ","xmonth":"10","xyear":"2015","QTY":"34"},{"omlPartgroupid":"197 ","xmonth":"11","xyear":"2015","QTY":"76"},{"omlPartgroupid":"197 ","xmonth":"12","xyear":"2015","QTY":"114"},{"omlPartgroupid":"197 ","xmonth":"1","xyear":"2016","QTY":"173"},{"omlPartgroupid":"197 ","xmonth":"2","xyear":"2016","QTY":"327"},{"omlPartgroupid":"197 ","xmonth":"3","xyear":"2016","QTY":"134"},{"omlPartgroupid":"197 ","xmonth":"4","xyear":"2016","QTY":"125"},{"omlPartgroupid":"197 ","xmonth":"5","xyear":"2016","QTY":"200"},{"omlPartgroupid":"197 ","xmonth":"6","xyear":"2016","QTY":"104"},{"omlPartgroupid":"197 ","xmonth":"7","xyear":"2016","QTY":"99"},{"omlPartgroupid":"197 ","xmonth":"8","xyear":"2016","QTY":"191"},{"omlPartgroupid":"197 ","xmonth":"9","xyear":"2016","QTY":"845"},{"omlPartgroupid":"197 ","xmonth":"10","xyear":"2016","QTY":"578"},{"omlPartgroupid":"199 ","xmonth":"10","xyear":"2015","QTY":"35"},{"omlPartgroupid":"199 ","xmonth":"11","xyear":"2015","QTY":"75"},{"omlPartgroupid":"199 ","xmonth":"12","xyear":"2015","QTY":"76"},{"omlPartgroupid":"199 ","xmonth":"1","xyear":"2016","QTY":"105"},{"omlPartgroupid":"199 ","xmonth":"2","xyear":"2016","QTY":"229"},{"omlPartgroupid":"199 ","xmonth":"3","xyear":"2016","QTY":"147"},{"omlPartgroupid":"199 ","xmonth":"4","xyear":"2016","QTY":"73"},{"omlPartgroupid":"199 ","xmonth":"5","xyear":"2016","QTY":"50"},{"omlPartgroupid":"199 ","xmonth":"6","xyear":"2016","QTY":"58"},{"omlPartgroupid":"199 ","xmonth":"7","xyear":"2016","QTY":"103"},{"omlPartgroupid":"199 ","xmonth":"8","xyear":"2016","QTY":"4230"},{"omlPartgroupid":"199 ","xmonth":"9","xyear":"2016","QTY":"2570"},{"omlPartgroupid":"199 ","xmonth":"10","xyear":"2016","QTY":"730"}];
var omlPartgroupid =[];
var xyear =[];
var xmonth =[];
var QTY=[];
var labelData = [];
for(var i in data){
omlPartgroupid.push("PartGroup"+ data[i].omlPartgroupid);
xyear.push(data[i].xyear);
xmonth.push(data[i].xmonth);
QTY.push(data[i].QTY);
labelData.push(data[i].xmonth + "|" + data[i].xyear + "|" + data[i].omlPartgroupid);
}
var chartdata ={
labels:labelData,
datasets :[
{
backgroundColor: 'rgba(200,200,200,0.75)',
borderColor: 'rgba(200,200,200,0.75)',
hoverBackground: 'rgba(200,200,200,1)',
hoverBorderColor: 'rgba(200,200,200,1)',
xAxisID:'time',
data:QTY
}
]
};
var ctx=$("#mycanvas");
var barGraph =new Chart(ctx,{
type: 'bar',
data: chartdata,
options: {
scales: {
xAxes:[ {
id: 'time',
type: 'category',
ticks: {
callback: function(label) {
var labelArray = label.split("|");
return labelArray[0] + "/" + labelArray[1];
}
}
},
{
id: 'partGroup',
type: 'category',
gridLines: {
drawOnChartArea: false, // only want the grid lines for one axis to show up
},
ticks: {
display:true,
callback: function(label) {
var labelArray = label.split("|");
return labelArray[0] === "10" && labelArray[1] == "2015" ? labelArray[2] : "";
}
}
}
]
}
}
});
<canvas id="mycanvas">

Razor chart.js labels/data not in sync

I have a Razor application that generates three columns of data to use in a chart graph. The page and javascript to do that looks like this:
<div><canvas id="myChart"></canvas></div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
var Maanden = [];
var Totalen = [];
#foreach (var m in Model.Grafieks)
{
#:Maanden.push("#m.maand" + "-" + "#m.jaar");
#:Totalen.push(#m.Total);
}
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: Maanden,
datasets: [
{ label: 'Facturen €',
data: Totalen,
backgroundColor: 'rgb(255, 255, 132)',
borderColor: 'rgb(255, 99, 132)',
borderWidth: 1,
}
]
},
});
</script>
Problem is that the labels are displayed OK but the data is off. Every second column is empty and its data pushed to the next column:
Chrome says:
Is there something wrong pushing the data into the arrays?
I had to convert the comma in decimal Totalen to a period!
#foreach (var m in Model.Grafieks)
{
#:Maanden.push("#m.maand" + "-" + "#m.jaar");
<text>bedrag = parsePotentiallyGroupedFloat("#m.Total");</text>
#:Totalen.push(bedrag);
}
function parsePotentiallyGroupedFloat(stringValue) {
stringValue = stringValue.trim();
var result = stringValue.replace(/[^0-9]/g, '');
if (/[,\.]\d{2}$/.test(stringValue)) {
result = result.replace(/(\d{2})$/, '.$1');
}
return parseFloat(result);
}
The function "parsePotentiallyGroupedFloat" is from here: Convert String with Dot or Comma as decimal separator to number in JavaScript

Inject html into ng2-chart tooltip to preview image

I have images with scores associated with them streaming to my app. As the scores come in I've plotted them on a line chart using ng2-charts.
I want to customize the tooltip on the chart to display a smaller preview of the image that it came with. I've scoured around but haven't been able to figure out how to inject the custom html into the tooltip or if it is even possible without creating a custom chart.
Any advice on whether or not this is possible and how would be greatly appreciated.
This is in Ionic 4 with angular 6 and my modules versions are:
"ng2-charts": "^2.2.2",
"chart.js": "^2.8.0",
Not sure this is necessary for my question but here's how I set up the chart so far.
Markdown
<ion-content padding>
<div class="row" style="display: block;">
<div class="col-md-6">
<div style="display: block;">
<canvas baseChart width="1200" height="600"
[datasets]="lineChartData"
[labels]="lineChartLabels"
[options]="lineChartOptions"
[colors]="lineChartColors"
[legend]="lineChartLegend"
[chartType]="lineChartType"
(chartHover)="chartHovered($event)"
(chartClick)="chartClicked($event)"></canvas>
</div>
</div>
</div>
</ion-content>
Initializing the chart
// Initializing Chart settings
public lineChartLegend:boolean = true;
public lineChartType:string = 'line';
public lineChartData:ChartDataSets[] = [{ data: this.scoreArr, label: 'Image Scores' }];
public lineChartLabels:Label[] = [];
public lineChartOptions: (ChartOptions & { annotation: any }) = {
responsive: true,
scales: {
// We use this empty structure as a placeholder for dynamic theming.
xAxes: [{}],
yAxes: [
{
id: 'y-axis-0',
position: 'left',
}
]
},
annotation: {
annotations: [
{
type: 'line',
mode: 'vertical',
scaleID: 'x-axis-0',
value: 'March',
borderColor: 'orange',
borderWidth: 2,
label: {
enabled: true,
fontColor: 'orange',
content: 'LineAnno'
}
},
],
}
};
public lineChartColors:Color[] = [
{ // dark grey
backgroundColor: 'rgba(77,83,96,0.2)',
borderColor: 'rgba(77,83,96,1)',
pointBackgroundColor: 'rgba(77,83,96,1)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgba(77,83,96,1)'
}
];
To anyone who is curious. This is how. However, the tooltip doesn't go away when you stop hovering but I'll figure it out in a bit.
customTooltips = function(tooltip) {
//**************** This is what was messing me up
var tooltipEl = document.getElementById('chartjs-tooltipsdfljsdflkswdjf');
// Apparently grabbing my existing tooltipel was causing my issue
// if you make tooltipel null and just make your own following the
// chart.js docs this will work fine.
// ***************
if (!tooltipEl) {
console.log("tooltipel was null");
tooltipEl = document.createElement('div');
tooltipEl.id = 'chartjs-tooltip';
tooltipEl.innerHTML = "<table></table>"
document.body.appendChild(tooltipEl);
}
// Hide if no tooltip
if (tooltip.opacity === 0) {
tooltipEl.style.opacity = '0';
return;
}
tooltipEl.classList.remove('above','below','no-transform');
if (tooltip.yAlign) {
tooltipEl.classList.add(tooltip.yAlign);
} else {
tooltipEl.classList.add('no-transform');
}
function getBody(bodyItem) {
return bodyItem.lines;
}
// Set Text
if (tooltip.body) {
console.log("Bodys not null: ", tooltip.body);
var titleLines = tooltip.title || [];
var bodyLines = tooltip.body.map(getBody);
var innerHtml = '<thead>';
titleLines.forEach(function(title) {
innerHtml += '<tr><th>' + title + '</th></tr>';
innerHtml += '<tr><th><img src="https://www.mariowiki.com/images/thumb/2/2b/Marioptds.png/146px-Marioptds.png" style="width:42px;height:42px;border:0;"/></th></tr>';
});
innerHtml += '</thead><tbody>';
bodyLines.forEach(function(body, i) {
var colors = tooltip.labelColors[i];
var style = 'background:' + colors.backgroundColor;
style += '; border-color:' + colors.borderColor;
style += '; border-width: 2px';
var span = '<span class="chartjs-tooltip-key" style="' + style + '"></span>';
innerHtml += '<tr><td>' + span + body + '</td></tr>';
});
innerHtml += '</tbody>';
var tableRoot = tooltipEl.querySelector('table');
console.log('TableRoot: ' + tableRoot);
tableRoot.innerHTML = innerHtml;
}
// `this` will be the overall tooltip
var position = this._chart.canvas.getBoundingClientRect();
// Display, position, and set styles for font
tooltipEl.style.opacity = '1';
tooltipEl.style.position = 'absolute';
tooltipEl.style.left = position.left + window.pageXOffset + tooltip.caretX + 'px';
tooltipEl.style.top = position.top + window.pageYOffset + tooltip.caretY + 'px';
tooltipEl.style.fontFamily = tooltip._bodyFontFamily;
tooltipEl.style.fontSize = tooltip.bodyFontSize + 'px';
tooltipEl.style.fontStyle = tooltip._bodyFontStyle;
tooltipEl.style.padding = tooltip.yPadding + 'px ' + tooltip.xPadding + 'px';
tooltipEl.style.pointerEvents = 'none';
};
// Initializing Chart settings
public lineChartLegend:boolean = true;
public lineChartType:string = 'line';
public lineChartData:ChartDataSets[] = [{ data: this.scoreArr, label: 'Image Scores' }];
public lineChartLabels:Label[] = [];
public lineChartOptions: (ChartOptions & { annotation: any }) = {
responsive: true,
scales: {
// We use this empty structure as a placeholder for dynamic theming.
xAxes: [{}],
yAxes: [
{
id: 'y-axis-0',
position: 'left',
}
]
},
annotation: {
annotations: [
{
type: 'line',
mode: 'vertical',
scaleID: 'x-axis-0',
value: 'March',
borderColor: 'orange',
borderWidth: 2,
label: {
enabled: true,
fontColor: 'orange',
content: 'LineAnno'
}
},
],
},
tooltips: {
enabled: false,
mode: 'index',
position: 'nearest',
custom: this.customTooltips
}
};
public lineChartColors:Color[] = [
{ // dark grey
backgroundColor: 'rgba(77,83,96,0.2)',
borderColor: 'rgba(77,83,96,1)',
pointBackgroundColor: 'rgba(77,83,96,1)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgba(77,83,96,1)'
}
];

Quill strips out simple html when dangerouslyPasteHTML into editor

<style>
#editor-container {
height: 375px;
}
.link {
color:blue;
}
</style>
<div id="editor-container">
This is a test
</div>
<script type="text/javascript">
var quill = new Quill('#editor-container', {
modules: {
toolbar: [
[{ header: [1, 2, false] }],
['bold', 'italic', 'underline'],
['image', 'code-block']
]
},
placeholder: 'Compose an epic...',
theme: 'bubble' // or 'bubble'
});
quill.clipboard.dangerouslyPasteHTML(5, "<span class=\"link\" data-test=\"test\">testing</span>", "silent");
</script>
MVCE - https://codepen.io/anon/pen/QMQMee
The HTML get stripped out despite being pretty harmless (this will be handled better later).
My current plan, due to the way Quill does not allow pasted html, is (As part of a click action on the mentioned person's name):
$("#tag-selectable-users-list li").on("click",
function() {
var $this = $(this);
var startIndex = $this.data("data-start-index");
var userName = $this.data("data-user-name");
var userId = $this.data("data-user-id");
var taggedUserIds = $("#hiddenTaggedUsers");
taggedUserIds.val((taggedUserIds.val()||"") + ";" + userId);
var delta = [];
if (startIndex > 0) {
//retain up to the tag start
delta.push({ retain: parseInt(startIndex) });
}
//delete the junk
delta.push({ delete: tagStatus.Total.length });
//insert the new characters
delta.push({
insert: "##" + userName,
attributes: {
color: "blue",
underline: "true"
}
});
//insert a blank space to end the span
delta.push({ insert: " " });
quill.updateContents(delta,
'api');
});
}

HighCharts : Xaxis lables misplaced

I want to label xaxis with values from JSON data that is happening but it is printing it at wrong place as shown in screenshot :
Here only seven values are present its labeled in that manner but actual data is plotted by leaving a gap of one. For example at 11th there is value and then again at 13t so total seven values but taking 14 places and label properly taking there first seven places how to match labels and bar graph
Following is my code snippet :
var obj = data[$("#host").val()].stats_vol.result.sectoutput;
var my_data_list = [];
var my_data_list1 = [];
var my_data_list2 = [];
var volumes = [];
for(var key in obj) {
var avg_latency = parseInt(obj[key].avg_latency);
var read_latency = parseInt(obj[key].read_latency);
var write_latency = parseInt(obj[key].write_latency);
console.log(key);
volumes.push(key);
my_data_list.push('Average Latency', parseInt(avg_latency));
my_data_list1.push('Read Latency', parseInt(read_latency));
my_data_list2.push('Write Latency', parseInt(write_latency));
}
$('#graphcontainer3').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Volume Level Latency'
},
yAxis: {
tickInterval: 100,
title: {
text: 'Latency(ms)'
}
},
xAxis: {
categories: volumes,
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:.1f} ms</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 2
}
},
series: [{
name: 'Average latency',
data: my_data_list,
}, {
name: 'Read Latency',
data: my_data_list1,
}, {
name: 'Write Latency ',
data: my_data_list2,
}]
});
Can anyone help me in this code to make this work fine???
I rectified the problem by myself :) It just I was giving labels two times
var obj = data[$("#host").val()].stats_vol.result.sectoutput;
var my_data_list3 = [];
var my_data_list1 = [];
var my_data_list2 = [];
var volumes = [];
for(var key in obj) {
var avg_latency = parseInt(obj[key].avg_latency);
var read_latency = parseInt(obj[key].read_latency);
var write_latency = parseInt(obj[key].write_latency);
console.log(avg_latency);
volumes.push(key);
my_data_list3.push(parseInt(avg_latency)); //here no need to give label again as it is done my volume(key)
my_data_list1.push( parseInt(read_latency));
my_data_list2.push(parseInt(write_latency));
}
This is what I was expecting as output .Hope it might be helpful for someone else hence answered.