1๐
โ
I get a rather self-explanatory error message with your code:
TypeError: Chart.data is undefined
The library can draw more than one chart in the same document. The simplest fix is to store it in a variable:
var myDoughnutChart = new Chart(document.getElementById("doughnut-chart"), {
type: 'doughnut',
data: {
labels: ["Male", "Female"],
datasets: [
{
label: "Population (millions)",
backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
data: [6,4]
}
]
},
options: {
title: {
display: true,
text: 'Predicted world population (millions) in 2050'
}
}
});
function addData(whatChart) {
whatChart.data.datasets[0].data[2] = 8;
whatChart.data.labels[2] = "Unknown";
whatChart.update();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.js"></script>
<div class="block">
<input type="button" value="Add Data" onclick="addData(myDoughnutChart)">
<canvas id="doughnut-chart" width="400" height="400"></canvas>
</div>
Source:stackexchange.com