简体   繁体   中英

Created an onclick function to remove data from a line chart in ChartsJs, but getting “Cannot read property 'data' of undefined” error

I was able to create a line chart with static data. Now, I am trying to create an onclick function that when you click, all the static data will be removed from the chart. I followed the documentation for chartsjs, but unfortunately it is not working. I am getting the following error: Cannot read property 'data' of undefined" . I find this odd because my data is defined as you can see below.

This is my first time working with charts and chartsjs, so any guidance is appreciated. Thank you.

Here is my Demo on JSFiddle

In my html, I added the onclick while you can see my removeData function.

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="line-chart" width="800" height="450"></canvas>
<button onclick="removeData()">Remove Data</button> 

Here is my JS. You can see my removeData function.

new Chart(document.getElementById("line-chart"), {
  type: 'line',
  data: {
    labels: [1500,1600,1700,1750,1800,1850,1900,1950,1999,2050],
    datasets: [{ 
        data: [86,114,106,106,107,111,133,221,783,2478],
        label: "Jonnies Pizza",
        borderColor: "#3e95cd",
        fill: false
      }
    ]
  },
  options: {
    title: {
      display: true,
      text: 'Pizza Sales Worldwide'
    }
  }
});



function removeData(chart) {
    chart.data.labels.pop();
    chart.data.datasets.forEach((dataset) => {
        dataset.data.pop();
    });
    chart.update();
}

The problem is that your removeData() function expects a chart object but you don't provide it in button onClick .

You can change your code as follows and it will work.

const chart = new Chart(document.getElementById("line-chart"), {
  type: 'line',
  data: {
    labels: [1500,1600,1700,1750,1800,1850,1900,1950,1999,2050],
    datasets: [{ 
        data: [86,114,106,106,107,111,133,221,783,2478],
        label: "Jonnies Pizza",
        borderColor: "#3e95cd",
        fill: false
      }
    ]
  },
  options: {
    title: {
      display: true,
      text: 'Pizza Sales Worldwide'
    }
  }
});      

function removeData() {
    chart.data.labels.pop();
    chart.data.datasets[0].data.pop();
    chart.update();
}

Please have a look at your amended JSFiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM