Chart.js inside in UpdatePanel using Bootstrap Modal - bootstrap-modal

I am trying to show Bar Chart in Bootstrap Modal Popup. But everything is fine when it is call outside UpdatePanel.
If I call the cart inside UpdatePanel, it is showing nothing. Please help me:
My jQuery:
<script type="text/javascript">
var randomScalingFactor = function () { return Math.round(Math.random() * 100) };
var lineChartData =
{
//labels: ["January", "February", "March", "April", "May", "June", "July"],
labels: <% =this.ChartLabels %>,
datasets:
[
{
label: "Query Count",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
//data: [0, 1, 4, 6, 10, 8, 6]
data: <% =this.ChartData1 %>
},
{
label: "My Second dataset",
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
//data: [28, 48, 40, 19, 86, 27, 90]
data: <% =this.ChartData2 %>
}
]
}
//Sys.WebForms.PageRequestManager.getInstance().add_endRequest(RunThisAfterEachAsyncPostback);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args) {
if (args.get_error() == undefined) {
DrawChart();
}
}
function DrawChart()
{
//Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
//Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx).Bar(lineChartData, {
responsive: true
});
}
$('#modChart').modal('show')
DrawChart();
</script>
I am calling the Jquery from CodeBehind :
protected void Button1_Click(object sender, EventArgs e)
{
public string ChartLabels = null;
public string ChartData1 = null;
public string ChartData2 = null;
this.ChartLabels = "['January', 'February', 'March', 'April', 'May', 'June', 'July']";
this.ChartData1 = "[65, 59, 80, 81, 56, 55, 40]";
this.ChartData2 = "[28, 48, 40, 19, 86, 27, 90]";
ScriptManager.RegisterStartupScript(this, this.GetType(), "CallMyFunction", "DrawChart()", true);
}
My ASPX Button inside in UpdatePanel:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div class="modal fade" id="modChart" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span><span class="sr-only">Close</span>
</button>
<h4 class="modal-title" id="exampleModalLabel">Linechart</h4>
</div>
<div class="modal-body">
<div>
<canvas id="canvas" width="568" height="300"></canvas>
</div>
</div>
</div>
</div>
</div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</ContentTemplate>
</asp:UpdatePanel>

Related

Django - display the same chart in loop in jinja template with chart.js

I would like to display the same chart (of course with different data and labels) in loop. At this moment I have:
<tbody>
{% for key, value in game_details.items %}
<tr>
<td>{{ key }}</td>
<td>{{ value.all }}</td>
<td>{{ value.win }}</td>
<td>{{ value.lost }}</td>
</tr>
<tr>
<td>
<canvas id="myChart" width="400" height="400"></canvas>
<script>
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ['Win', 'Lost'],
datasets: [{
label: '# of Votes',
data: [{{ value.win }}, {{ value.lost }}],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
</script>
</td>
</tr>
{% endfor %}
</tbody>
The first chart is displayed, but when I'm looking in console I can see: Uncaught SyntaxError: Identifier 'ctx' has already been declared (at (index):179:29). So my loop can't create another chart, because ctx is already declared. My goal is to display chart for each iteration over dictionary. I was looking at this post, but it doesn't sole my problem. How can I do it properly?
Construct your canvas identifier and those JavaScript constant names with the loop index loop.index:
For example:
{% for key, value in game_details.items %}
<canvas id="myChart{{ loop.index }}" width="400" height="400"></canvas>
<script>
const ctx{{ loop.index }} = document.
getElementById('myChart{{ loop.index }}').
getContext('2d');
const myChart{{ loop.index }} = new Chart(ctx{{ loop.index }}, {
type: 'pie',
data: {
labels: ['Win', 'Lost'],
datasets: [{
label: '# of Votes',
data: [{{ value.win }}, {{ value.lost }}],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
</script>
{% endfor %}

Chart.js coming up as blank

I'm using chart.js in a plain JavaScript page and the chart is coming up as blank. I am not getting any errors in the Google Chrome console. Below is the code I am using
<!DOCTYPE html>
<html lang="en">
<head th:replace="fragments/header :: head('Home')"></head>
<body>
<header th:replace="fragments/header :: header"> </header>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<div class="container">
<div>
<canvas id="myChart" width="200" height="200"></canvas>
</div>
</div>
<script>
const labels = [
'January',
'February',
'March',
'April',
'May',
'June',
];
const chartData = {
labels: labels,
datasets: [{
label: 'My First dataset',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [0, 10, 5, 2, 20, 30, 45],
}]
};
const config = {
type: 'line',
chartData,
options: {}
};
var myChart = new Chart(
document.getElementById('myChart'),
config
);
</script>
<!-- Bootstrap core JavaScript -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>
<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script>
</body>
Can chart.js be using with plain JavaScript? Is there anything wrong with the code I am using?
Please assign data key in config to assign chartdata
const labels = [
'January',
'February',
'March',
'April',
'May',
'June',
];
const chartData = {
labels: labels,
datasets: [{
label: 'My First dataset',
data: [0, 10, 5, 2, 20, 30, 45],
}]
};
const config = {
type: 'line',
data: chartData,
options: {}
};
var myChart = new Chart(
document.getElementById('myChart'),
config
);
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<div class="container">
<div>
<canvas id="myChart" width="200" height="200"></canvas>
</div>
</div>

Chart.js - Multiple bar Charts - Only Show Last Chart

Chart.js - Multiple Bar Charts - Only Show Last Chart.Basically data comes from django and is rendered in the template.Data is proper but only one of 2 charts are being rendered.
I also tried changing ctx but it did not worked
HTML Code
<div class="container">
<div id="container" class="col-6">
<canvas id="indiacanvas"></canvas>
</div>
<div id="container" class="col-6">
<canvas id="usacanvas"></canvas>
</div>
</div>
Basically data comes from django and is rendered in the template.Data is proper but only one of 2 charts are being rendered.
I also tried changing ctx but it did not worked
Script.js
//BAR CHART USD
var barChartData = {
labels: [{% for item in listyear1 %}'{{item| date:"Y"}}', {% endfor %}],
datasets: [
{
label: "Total amount",
backgroundColor: "lightblue",
borderColor: "blue",
borderWidth: 1,
data: [{% for inr in USATOTAL %}'{{inr}}', {% endfor %}],
},
{
label: "Amount Recieved",
backgroundColor: "lightgreen",
borderColor: "green",
borderWidth: 1,
data: [{% for rinr in RUSDS %} '{{rinr}}', {% endfor %}],
},
{
label: "Amount Left",
backgroundColor: "pink",
borderColor: "red",
borderWidth: 1,
data: [{% for linr in LUSDS %} '{{linr}}', {% endfor %}],
},
],
};
var chartOptions = {
responsive: true,
legend: {
position: "top",
},
title: {
display: true,
text: "YearWise Summary USD",
},
scales: {
yAxes: [
{
ticks: {
beginAtZero: true,
},
},
],
},
};
window.onload = function () {
var ctx = document.getElementById("usacanvas").getContext("2d");
window.myBar = new Chart(ctx, {
type: "bar",
data: barChartData,
options: chartOptions,
});
};
// Bar Chart India
var barChartData = {
labels: [{% for item in listyear %}'{{item| date:"Y"}}', {% endfor %}],
datasets: [
{
label: "Total amount",
backgroundColor: "lightblue",
borderColor: "blue",
borderWidth: 1,
data: [{% for inr in INDIATOTAL %}'{{inr}}', {% endfor %}],
},
{
label: "Amount Recieved",
backgroundColor: "lightgreen",
borderColor: "green",
borderWidth: 1,
data: [{% for rinr in RINR %} '{{rinr}}', {% endfor %}],
},
{
label: "Amount Left",
backgroundColor: "pink",
borderColor: "red",
borderWidth: 1,
data: [{% for linr in LINR %} '{{linr}}', {% endfor %}],
},
],
};
var chartOptions = {
responsive: true,
legend: {
position: "top",
},
title: {
display: true,
text: "YearWise Summary INR",
},
scales: {
yAxes: [
{
ticks: {
beginAtZero: true,
},
},
],
},
};
window.onload = function () {
var ctx = document.getElementById("indiacanvas").getContext("2d");
window.myBar = new Chart(ctx, {
type: "bar",
data: barChartData,
options: chartOptions,
});
};
Due to JavaScripts async nature, ctx might get reassigned. Try using ctx2 as variable name for the second chart.

Chartjs Overlap click function doesnt work

I have a simple line chart and I have problem when two or more points are too closer. The problem is: The tooltip show one point and the click function is for other point.
In this exemple you can see that when I click on the first point on the red line (value 2) the click event is for the black line (value 0)
Exemple:
https://codepen.io/ataufo/pen/NexppY
var canvas = document.getElementById("lineChart");
var ctx = canvas.getContext('2d');
var data = {
labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
datasets: [{
label: "Stock A",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(225,0,0,0.4)",
borderColor: "red",
borderCapStyle: 'square',
pointBorderWidth: 0.1,
pointHoverRadius: 6,
pointHoverBorderWidth: 2,
pointRadius: 1,
data: [2, 59, 80, 81, 56],
spanGaps: false,
datalabels: {
enabled: true,
allowOverlap: true,
display: true,
listeners: {
click: function(context) {
alert(context.dataIndex + " Red line");
}
}
}
}, {
label: "Stock B",
fill: false,
lineTension: 0.1,
backgroundColor: "black",
borderColor: "black",
borderCapStyle: 'square',
pointBorderWidth: 0.1,
pointHoverRadius: 6,
pointHoverBorderWidth: 2,
pointRadius: 1,
data: [0, 20, 60, 95, 64],
spanGaps: false,
datalabels: {
enabled: true,
allowOverlap: true,
display: true,
listeners: {
click: function(context) {
alert(context.dataIndex + " Black Line");
}
}
}
}
]
};
// Chart declaration:
var myBarChart = new Chart(ctx, {
showTooltips: false,
type: 'line',
data: data
});
Does anyone have one idea to solve that?
You explicitly reference dataset 0. You need to pass the dataset index like so:
canvas.onclick = function(evt) {
var activePoints = myLineChart.getElementAtEvent(evt);
//console.log(activePoints);
if (activePoints[0]) {
var chartData = activePoints[0]['_chart'].config.data;
var idx = activePoints[0]['_index'];
var label = chartData.labels[idx];
// change the following line...
//var value = chartData.datasets[0].data[idx];
// to this:
var value = chartData.datasets[activePoints[0]._chart.tooltip._active[0]._datasetIndex].data[idx];
var url = "Mês:" + label + " Valor: " + value;
alert(url);
}
};
Edit: Fully working example.
var canvas = document.getElementById("lineChart");
var ctx = canvas.getContext('2d');
canvas.onclick = function(evt) {
var activePoints = myLineChart.getElementAtEvent(evt);
console.log(activePoints);
if (activePoints[0]) {
var chartData = activePoints[0]['_chart'].config.data;
var idx = activePoints[0]['_index'];
var label = chartData.labels[idx];
//var value = chartData.datasets[0].data[idx];
var value = chartData.datasets[activePoints[0]._chart.tooltip._active[0]._datasetIndex].data[idx];
var url = "Mês:" + label + " Valor: " + value;
alert(url);
}
};
var data = {
labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
datasets: [{
label: "Stock A",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(225,0,0,0.4)",
borderColor: "red",
borderCapStyle: 'square',
pointBorderWidth: 0.1,
pointHoverRadius: 6,
pointHoverBorderWidth: 2,
pointRadius: 1,
data: [2, 59, 80, 81, 56],
spanGaps: false
}, {
label: "Stock B",
fill: false,
lineTension: 0.1,
backgroundColor: "black",
borderColor: "black",
borderCapStyle: 'square',
pointBorderWidth: 0.1,
pointHoverRadius: 6,
pointHoverBorderWidth: 2,
pointRadius: 1,
data: [0, 20, 60, 95, 64],
spanGaps: false
}
]
};
// Chart declaration:
var myLineChart = new Chart(ctx, {
type: 'line',
data: data,
options: {
tooltips: {
enabled: true
}
}
});
body{
background-color: #666;
}
#lineChart{
background-color: wheat;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>
<div class="container">
<br />
<div class="row">
<div class="col-md-1"></div>
<div class="col-md-10">
<!-- Chart.js Canvas Tag -->
<canvas id="lineChart"></canvas>
</div>
<div class="col-md-1"></div>
</div>
</div>

Chart.js 2.0 - Tooltip is showing incomplete data on hover

The tooltip is showing details of only on data point instead of showing all values which are under the label. I want to show all details in the toolbar, let's say when user hover on the point which has label 1 then it's should show following in the tooltip. here is the jsbin.
1
Prime and Fibonacci: 2
My Second dataset: 2
<!doctype html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Line Chart Test</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.0.2/Chart.min.js"></script>
<script language="JavaScript"><!--
function displayLineChart() {
var data = {
labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
datasets: [
{
label: "Prime and Fibonacci",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
},
{
label: "My Second dataset",
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "red",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
data: [2, 3, 5, 7, 11, 13, 17, 13, 21, 34]
}
]
};
var holder = document.getElementById('lineChart');
var options = {};
new Chart(holder, {
type: 'line',
data: data,
options: {
responsive: true
}
});
}
--></script>
</head>
<body onload="displayLineChart();">
<div class="box">
<canvas id="lineChart" height="450" width="800"></canvas>
</div>
</body>
</html>
You can use a tooltip call back function, read thread here. I have updated your function below and you are ready to go. Good luck!
function displayLineChart() {
var data = {
labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
datasets: [
{
label: "Prime and Fibonacci",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
},
{
label: "My Second dataset",
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "red",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
data: [2, 3, 5, 7, 11, 13, 17, 13, 21, 34]
}
]
};
var holder = document.getElementById('lineChart');
var options = {};
new Chart(holder, {
type: 'line',
data: data,
options: {
responsive: true,
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
console.log(tooltipItem);
console.log( data.datasets[0])
var value = data.datasets[0].data[tooltipItem.index];
var label = data.labels[tooltipItem.index];
var datah = [];
datah.push(data.datasets[0].label + ' ' + value);
datah.push(data.datasets[1].label + ' ' + value);
return datah;
}
}
}
}
});
}