Chartjs-Error trying to switch between different charts

1👍

You can invoke your updateChart function with the selected chart type as follows:

onchange="updateChart(this.value)"

Everything could then be done inside the updateChart function.

  1. destroy the chart if it already exists
  2. create the new chart with the specified type

To make this work, you’ll also have to explicitly invoke updateChart once with the initial chart type.

updateChart('pie');

Please take a look at below runnable code snippet and see how it works.

let myChart;
function updateChart(type) {
  if (myChart) {
    myChart.destroy();
  }
  myChart = new Chart('chart', {
    type: type,
    data: {
      labels: ['A', 'B'],
      datasets: [{
        data: [3, 6],
        backgroundColor: ['#252850', '#f44611']
      }]
    },
    options: {
      scales: {
        yAxes: [{
          display: type == 'bar',
          ticks: {
            beginAtZero: true
          }
        }]
      }
    }
  });
}
updateChart('pie');
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<select name="chartType" id="chartType" onchange="updateChart(this.value)" data-role="select">
  <option value="pie">Pie</option>
  <option value="bar">Bar</option>
</select>
<canvas id="chart" height="100"></canvas>

Leave a comment