Reputation: 304
I've got an issues with ChartJS (or my stupidity). I've created a fiddle to show the problem.
Here is a JSFiddle of the exact issue:
var ctx = document.getElementById('somechart').getContext('2d');
var somechart = new Chart(ctx, {
type: 'line',
options: {
title: {
display: true,
text: 'Custom Chart Title'
}
},
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'My First dataset',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [0, 10, 5, 2, 20, 30, 45]
}],
},
});
somechart.options.title.text = 'new title';
somechart.config.data.datasets.data[2] = 5000;
somechart.update();
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<canvas id="somechart"></canvas>
I'm trying to update the chart after it has been rendered. However I'm getting a console error
Uncaught TypeError: Cannot read property 'title' of undefined at window.onload
EDIT: The variable name did not match, I have fixed this. Still getting an error "jquery.min.js:2 Uncaught TypeError: Cannot set property '2' of undefined at HTMLDocument."
Upvotes: 0
Views: 1150
Reputation: 327
you are using the wrong variable for updating content replace your somechart to chart as you have initialize chart variable
var chart = new Chart
https://drive.google.com/uc?id=1QTdQsZqGMnmNZ2LrCed_yIWUQbg4hO5s
Updated your code as below
chart.options.title.text = 'new title';
chart.config.data.datasets[0].data[2] = 5000;
chart.update();
you need to specify the index of the dataset in order to update the data.
Upvotes: 2
Reputation: 968
Seems to have been a couple of issues:
somechart
doesn't exist, you named it chart
chart.config.data.datasets.data[2] = 5000;
will not work because datasets is an array, so you can access it like this: chart.config.data.datasets[0].data[2] = 5000;
Heres a new fiddle with the fixes above added: https://jsfiddle.net/8whzsLgp/
Upvotes: 2
Reputation: 9273
Your chart variable is named chart
but you're trying to access it via somechart
, which does not exist. Change the variable somechart
to chart
.
Upvotes: 1