Chart js adding number

750 views Asked by At

I'm trying to update the data inside my donut chart and my addData function does not seem to work when pressing the Add Data button. I'm suppose to add "unknown" as another label with data of 8. Please help.

 <DOCTYPE html>
<html>
<head>
 <title>ChartJS - Pie Chart</title>
    <script src="jquery-3.2.1.js"></script>
    <script 
 src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.js">
 </script>
    <link rel="stylesheet" type="text/css" href="template.css">
 </head>
 <body>
 <div class="block">        
  <input type="button" value="Add Data" onclick="addData()">
 <canvas id="doughnut-chart" width="400" height="400"></canvas>
 <script>
 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() {
Chart.data.datasets[0].data[2] = 8;
Chart.data.labels[2] = "Unknown";
Chart.update();
}
</script>
</div>
</body>
</html>
1

There are 1 answers

0
Álvaro González On BEST ANSWER

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>