Chartjs-How to change chart js data on button click

0πŸ‘

To update the chart, you will have to invoke update method of the chart as below:

myChart.update();

0πŸ‘

I saw your question as well on youtube but somehow it was suddenly gone. However I created the video covering complete details and you can also see the mistakes you made in your code and how I convert it into a working chart which updates on click. Watch full explanation here: https://youtu.be/YA4ZgurFWV0

    <div class="chartBox">
  <canvas id="myChart"></canvas>
</div>

<div class="center">
  <input type="number" id="value1">
  <input type="number" id="value2">
  <button id="updateChart">Update</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<script>
// setup block
const data1 = 55;
const data2 = 11;
const data = {
  labels: ['data1', 'data2'],
    datasets: [{ // index 0
      label: 'Amount',
      data: [data1, data2],
      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,
      cutout: '90%'
    }]

  };

// config block
const config = {
  type: 'doughnut',
    data: data,
    options: {
    scales: {}
  }
};

// render /init block      
const myChart = new Chart(
  document.getElementById('myChart'),
  config
);

const value1 = document.getElementById('value1');
const value2 = document.getElementById('value2');
value1.value = data1;
value2.value = data2;

const updateChart = document.getElementById('updateChart');
updateChart.addEventListener('click', updateDoughnutChart);

function updateDoughnutChart(){
  myChart.data.datasets[0].data[0] = value1.value;
  myChart.data.datasets[0].data[1] = value2.value;
  myChart.update();
}

</script>

Leave a comment