Custom tooltip in Chart.js - asp.net

I'm trying to display custom tool tips with Chart.js depending on the data classification. I want to display:
1: Tooltip1
2: Tooltip2
3: Tooltip2
Following is the code.
<script type="text/javascript" language="javascript">
var pieData = [
{
value: parseInt(document.getElementById("<%= txtPendingCount.ClientID %>").value, 0),
color: "#f5170a",
highlight: "#f85248",
label: "1"
},
{
value: parseInt(document.getElementById("<%= txtCompletedCount.ClientID %>").value, 0),
color: "#ce5e0c",
highlight: "#cf7d40",
label: "2"
},
{
value: parseInt(document.getElementById("<%= txtWithheldCount.ClientID %>").value, 0),
color: "#f4cd0c",
highlight: "#f7de62",
label: "3"
}
];
window.onload = function () {
var ctx = document.getElementById("chart-area").getContext("2d");
window.myPie = new Chart(ctx).Pie(pieData);
};
</script>
Can anyone please suggest how to do this?
Thanks.

In the example you can see how to do this, you can note that i use doughut but is the same idea to do this with pie chart:
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="chart-area" style="display:inline;"></canvas>
<script>
var doughnutData = [
{
value: 200,
color: "#FFF",
label:"White",
},
{
value: 200,
color: "#bb2028",
label:"Red",
},
{
value: 80,
color: "#d97128" ,
label:"Orange",
},
{
value: 40,
color: "#fada09",
label:"Yellow",
},
{
value: 100,
color: "#6bb345",
label:"Light Green",
},
{
value: 60,
color: "#b4aea7",
label:"Gray",
},
{
value: 200,
color:"#2d5f2e",
fillColor:"#2d5f2e",
label:"Green",
}
];
window.onload = function(){
var helpers = Chart.helpers;
var canvas= document.getElementById("chart-area");
var ctx = canvas.getContext("2d");
var globalChartConfig = {
responsive : true,
tooltipTemplate: "<%if (label){%>Label Color: <%=label%>: <%}%> <%= value %>",
}
window.myDoughnut = new Chart(ctx).Doughnut(doughnutData, globalChartConfig);
};
</script>

Related

Ajax and error cannot read properties of undefined

So I am trying to get some data from a table using ajax but this error keeps popping up and I know its related to parameters but I have none of the parameters it says are wrong anyone got any ideas?
I am working in asp.net 6 and am trying to get the data to a controller.
I am currently working in C# and ajax
(function () {
"use strict"
window.onload = function () {
//Reference the DropDownList.
var ddlYears = document.getElementById("ddlYears");
//Determine the Current Year.
var currentYear = (new Date()).getFullYear() + 10;
var less = (new Date()).getFullYear() - 10;
//Loop and add the Year values to DropDownList.
for (var i = less; i <= currentYear; i++) {
var option = document.createElement("OPTION");
option.innerHTML = i;
option.value = i;
ddlYears.appendChild(option);
}
};
var ScopeTable;
$(document).ready(function () {
ScopeTable = $("#tblScopeView").DataTable({
dom: "Bfrtip",
paging: true,
pagingType: "full_numbers",
buttons: [
"csvHtml5"
],
columns: [
{ data: 'WBS' },
{ data: 'Title' },
{ data: 'Rev' },
{ data: 'ScopeStatus' },
{ data: 'BCP' },
{ data: 'BCPApprovalDate' },
{ data: 'Manager' },
{ data: 'ProjectControlManager' },
{ data: 'ProjectControlEngineer' },
{
mRender: function (data, type, row) {
return "<i class='fa fa-edit btnAddEditScope'></i><span> Edit</span >"
},
class: "btnAddEditScope table-button",
orderable: false
},
{
mRender: function (data, type, row) {
return "<i class='fa fa-trash btnDeleteRow'></i><span> Delete</span >"
},
orderable: false,
class: "table-button"
}
],
createdRow: function (row, data, index) {
$(row).attr("data-id", data.WBSNumber);
$(row).attr("data-month", data.FiscalMonth);
$(row).attr("data-year", data.FiscalYear);
}
});
$(document).on("click", ".btnAddEditScope", btnAddEditScope_click);
$("#spnrSave").hide();
});
function btnAddEditScope_click() {
console.log("button clicked")
$.ajax({
url: "Scope/AddEditScope",
type: "GET",
success: function () {
$("#vw_AddEditScope").modal("show");
}
});
}
}());
Error that is being posted
Figured it out just had do adjust my ajax and it worked fine. The tutorial I found is here https://datatables.net/examples/api/multi_filter.html
var ScopeTable;
$(document).ready(function (e) {
ScopeTable = $("#tblScopeView").DataTable({
dom: "Bfrtip",
paging: true,
pagingType: "full_numbers",
buttons: [
"csvHtml5"
],
columns: [
{ data: 'WBS' },
{ data: 'Title' },
{ data: 'Rev' },
{ data: 'ScopeStatus' },
{ data: 'BCP' },
{ data: 'BCPApprovalDate' },
{ data: 'Manager' },
{ data: 'ProjectControlManager' },
{ data: 'ProjectControlEngineer' },
{
mRender: function (data, type, row) {
return "<i class='fa fa-edit btnAddEditScope'></i><span> Edit</span >"
},
class: "btnAddEditScope table-button",
orderable: false
}, {
mRender: function (data, type, row) {
return "<i class='fa fa-trash btnDeleteRow'></i><span> Delete</span >"
},
orderable: false,
class: "table-button"
},
],
createdRow: function (row, data, index) {
$(row).attr("data-id", data.WBSNumber);
$(row).attr("data-month", data.FiscalMonth);
$(row).attr("data-year", data.FiscalYear);
},
error: function (e) {
console.log(e);
}
});
$('#tblScopeView tfoot th').each(function () {
var title = $("#tblScopeView").eq($(this).index()).text();
$(this).html('<input type="text" class="form-control" placeholder="Search ' + title + '" />');
ScopeTable.columns().every(function () {
var dataTableColumn = this;
$(this.footer()).find('input').on('keyup change', function () {
dataTableColumn.search(this.value).draw();
});
});
});
$("#spnrSave").hide();
$(document).on("click", ".btnAddEditScope", btnAddEditScope_click);
});

Zoom to Marker location on click -OpenLayers

I am displaying markers on the map from geojson file. In the current code, I can add the markers on the map. I want to add fly to or zoom in marker exact location upon click on the marker.how can I achieve that using OpenLayers.
var cityMarker = new ol.layer.Vector({
source: new ol.source.Vector({
format: new ol.format.GeoJSON(),
url: "data/cities.js"
}),
style: new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 0.5],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
scale:0.03,
src: "icons/red-circle.png"
})
})
});
map.addLayer(cityMarker);
bind singleclick event to map
map.on('singleclick', event => {
// get the feature you clicked
const feature = map.forEachFeatureAtPixel(event.pixel, (feature) => {
return feature
})
if(feature instanceof ol.Feature){
// Fit the feature geometry or extent based on the given map
map.getView().fit(feature.getGeometry())
// map.getView().fit(feature.getGeometry().getExtent())
}
})
A separate HTML file for you!
<!DOCTYPE html>
<html>
<head>
<title>GeoJSON</title>
<link
rel="stylesheet"
href="https://openlayers.org/en/v4.6.5/css/ol.css"
type="text/css"
/>
<!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
<script src="https://openlayers.org/en/v4.6.5/build/ol.js"></script>
</head>
<body>
<div id="map" class="map"></div>
<script>
var image = new ol.style.Circle({
radius: 5,
fill: null,
stroke: new ol.style.Stroke({ color: "red", width: 1 }),
});
var styles = {
Point: new ol.style.Style({
image: image,
}),
};
var styleFunction = function (feature) {
return styles[feature.getGeometry().getType()];
};
var geojsonObject = {
type: "FeatureCollection",
crs: {
type: "name",
properties: {
name: "EPSG:3857",
},
},
features: [
{
type: "Feature",
geometry: {
type: "Point",
coordinates: [0, 0],
},
},
{
type: "Feature",
geometry: {
type: "Point",
coordinates: [13369643, 3572500],
},
},
],
};
var vectorSource = new ol.source.Vector({
features: new ol.format.GeoJSON().readFeatures(geojsonObject),
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource,
style: styleFunction,
});
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM(),
}),
vectorLayer,
],
target: "map",
controls: ol.control.defaults({
attributionOptions: {
collapsible: false,
},
}),
view: new ol.View({
center: [0, 0],
zoom: 2,
}),
});
map.on("singleclick", (event) => {
// get the feature you clicked
const feature = map.forEachFeatureAtPixel(event.pixel, (feature) => {
return feature;
});
if (feature instanceof ol.Feature) {
// Fit the feature geometry or extent based on the given map
map.getView().fit(feature.getGeometry());
// map.getView().fit(feature.getGeometry().getExtent())
}
});
</script>
</body>
</html>

Show values on google piechart legends

I have this google piechart, which is working fine, except on the legend text along with it, I wanna show the percentage and numbers. The below would be the code
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var options = {
title: 'Registration',
legend: { position: 'right', textStyle: { color: 'blue', fontSize: 16 } }
};
$.ajax({
type: "POST",
url: "adminrep.aspx/GetChartData",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var data = google.visualization.arrayToDataTable(r.d);
var chart = new google.visualization.PieChart($("#chart")[0]);
chart.draw(data, options);
},
failure: function (r) {
alert(r.d);
},
error: function (r) {
alert(r.d);
}
});
}
</script>
<div id="chart" style="width: 900px; height: 500px; margin-top:60px;"></div>
How do I get this done? Thanks in advance.
Try using .setFormattedValue to format the the labels in the DataTable.
This still requires you do a little bit of manual calculation for the getting the total sum of values, but it should work:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var options = {
title: 'Registration',
legend: {
position: 'right',
textStyle: { color: 'blue', fontSize: 16 }
}
};
$.ajax({
type: "POST",
url: "/echo/json/",
data: {
json: JSON.stringify({
d: [
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]})
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var data = google.visualization.arrayToDataTable(r.d);
var count = data.getNumberOfRows();
var values = Array(count).fill().map(function(v, i) {
return data.getValue(i, 1);
});
var total = google.visualization.data.sum(values);
values.forEach(function(v, i) {
var key = data.getValue(i, 0);
var val = data.getValue(i, 1);
data.setFormattedValue(i, 0, key + ' (' + (val/total * 100).toFixed(1) + '%)');
});
var chart = new google.visualization.PieChart($("#chart")[0]);
chart.draw(data, options);
},
failure: function (r) {
alert(r.d);
},
error: function (r) {
alert(r.d);
}
});
}
</script>
<div id="chart" style="width: 900px; height: 500px; margin-top:60px;"></div>
Example: https://jsfiddle.net/cn74tvmL/show
You need to use number format:
var formatter = new google.visualization.NumberFormat({pattern: '#,### MW'});
formatter.format(data, 1);
or:
chart1.options = {
.
.
.
pieSliceText: 'value',
legend: {
position: 'labeled',
labeledValueText: 'both',
textStyle: {
color: 'blue',
fontSize: 14
}
}
};

Problem in making chart with Chart.js in wix?

I am having a problem in building a pie chart with chart.js ..I am working in wix.com ..The problem i am facing is with 2 postmessage()..
Here is the page code....
import wixData from 'wix-data';
import { session } from 'wix-storage';
var name = session.getItem('name');
var platformName = session.getItem('platform');
import { getchampionranks } from 'backend/pcprofile.jsw';
$w.onReady(function () {
getchampionranks('pronil07').then(res => {
console.log(res);
var data = [];
var labels = [];
for (var i = 0; i <= res.length - 1; i++) {
data.push(res[i].Minutes.toString());
labels.push(res[i].champion.toString());
}
console.log(data);
console.log("Data length: " + data.length);
console.log(labels);
console.log("Label length: " + labels.length);
$w("#html1").postMessage(data);
//$w("#html1").postMessage(labels);
});
});
Here is the iframe code...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src ="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.js"></script>
</head>
<body onLoad="ready()">
<canvas id="myChart" width="146" height="149"></canvas>
<script>
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: [],
datasets: [{
label: 'wins/loss',
data: [],
backgroundColor: [
'#3ddba1',
'#e02a2a',
'#4286f4',
'#6897e2',
'#444a54',
'#45a567',
'#91a545',
'#a87534',
'#8c6e8a'
],
borderWidth: 1
}]
},
options: {
cutoutPercentage : 0,
rotation: Math.PI * 0.8,
legend:{
display: false,
position: 'bottom',
},
animation: {
easing: 'easeOutElastic',
Steps: 100,
animateRotate : true,
animateScale : true
}
}
});
window.onmessage = function(event){
myChart.data.datasets[0].data = event.data;
myChart.update();
};
function ready(){
window.parent.postMessage({"type":"ready"}, "*");
}
</script>
</body>
</html>
On doing this..i am getting the result like this..
Result
I am getting the chart with the data array..but the labels is undefined..
And if i unquote the postmessage(labels) and send both data and labels via 2 postmessage()..the chart don't form...
I need to send both data and labels array to the iframe from page code...
Any solution?????
This is easiest done by sending both the data and the labels from your page code in one object. Then in the HTML element, you can set the chart's data and labels using that object.
In your case, that would look something like this:
Page Code:
let info = {data:data, labels:labels};
$w("#html1").postMessage(info);
HTML Element Code:
window.onmessage = function(event){
myChart.data.datasets[0].data = event.data.data;
myChart.data.labels = event.data.labels;
myChart.update();
};
You are right! This is the easiest way.
Here is the page code...
var data = [];
for (var i = 1; i < 7; i++) {
var _temp = Math.log10(i);
data.push(_temp);
}
var labels = ["September", "October", "Novemver", "December", "January", "February"];
$w.onReady(() => {
console.log("Data length: " + data.length);
console.log(data);
console.log("Label length: " + labels.length);
console.log(labels);
$w("#html1").onMessage((event) => {
let info = { data: data, labels: labels };
if (event.data.type === 'ready') {
$w("#html1").postMessage(info);
}
});
});
Here is the html code...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src ="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.js">
</script>
</head>
<body onLoad="ready()">
<canvas id="myChart" width="250" height="200"></canvas>
<script>
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: [],
datasets: [{
label: 'Our activity',
data: []
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
window.onmessage = function(event){
myChart.data.datasets[0].data = event.data.data;
myChart.data.labels = event.data.labels;
myChart.update();
};
function ready(){
window.parent.postMessage({"type":"ready"}, "*");
}

CanvasJs not displaying line in .asp

Guys the problem i have with it is that i am not able to see the line chart's line and points. i am pretty sure that the chart is working because when i hover across it, i am able to see the data points. Please help, thanks!
This is the JavaScript for it.
<script type = "text/javascript" >
window.onload = function () {
var dataPoints = [{ y: 10 }];
var chart = new CanvasJS.Chart("chartContainer", {
backgroundColor: "red",
title: {
text: "Dynamic Data"
},
axisY: {
},
data: [{
type: "spline",
color: "yellow",
dataPoints: dataPoints
}]
});
chart.render();
var yVal = 15, updateCount = 0;
var updateChart = function () {
yVal = yVal;
updateCount++;
dataPoints.push({
y: yVal
});
chart.options.title.text = "Update " + updateCount;
chart.render();
};
// update chart every second
setInterval(function () { updateChart() }, 1000);
}
</script>
This is the body for it.
<div id = "chartContainer" style = "height: 300px; width: 100%;" />
I am unable to reproduce the issue.Can you share more details like the browser & CanvasJS library version. Here is a working fiddle for your code without any modification.
var dataPoints = [{ y: 10 }];
var chart = new CanvasJS.Chart("chartContainer", {
backgroundColor: "red",
title: {
text: "Dynamic Data"
},
axisY: {
},
data: [{
type: "spline",
color: "yellow",
dataPoints: dataPoints
}]
});
chart.render();
var yVal = 15, updateCount = 0;
var updateChart = function () {
yVal = yVal;
updateCount++;
dataPoints.push({
y: yVal
});
chart.options.title.text = "Update " + updateCount;
chart.render();
};
// update chart every second
setInterval(function () { updateChart() }, 1000);

Resources