Changing Chart Type from Dropdown with data from external JSON & Creating multiple charts if its pie/doughnut - CanvasJS JavaScript Charts

Changing Chart Type from Dropdown with data from external JSON & Creating multiple charts if its pie/doughnut - CanvasJS JavaScript Charts

by canvasjs

HTML

<script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script src="https://canvasjs.com/assets/script/jquery.canvasjs.min.js"></script>
<div>Chart Type:
  <select id="chartType" name="Chart Type">    
    <option value="column">Column</option>
    <option value="line">Line</option>
    <option value="bar">Bar</option>
    <option value="pie">Pie</option>
    <option value="doughnut">Doughnut</option>
  </select>  
</div>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>

JavaScript

var dataSeries = [];
var dataPoints = [];

var chart = new CanvasJS.Chart("chartContainer", {
	animationEnabled: true,
	theme: "light2",
	title: {
		text: "Daily Sales Data"
	},
	axisY: {
		title: "Units",
		titleFontSize: 24
	},
	data: dataSeries
});

function addData(data) {
	for (var i = 0; i < data.length; i++) {
  	dataPoints = [];
  	for(var j = 0; j < data[i].length; j++){
      dataPoints.push({
        x: new Date(data[i][j].date),
        y: data[i][j].units
      });
    }
    dataSeries.push({
        type: "column",
        yValueFormatString: "#,### Units",
        dataPoints: dataPoints
		});
	}
	chart.render();

}

$.getJSON("https://api.myjson.com/bins/1am4t6", addData);


var chartOptions = chart.options;
var chartType = document.getElementById('chartType');
var containerId = null;

chartType.addEventListener( "change",  function(){
	if(chartType.options[chartType.selectedIndex].value === "pie" || chartType.options[chartType.selectedIndex].value === "doughnut"){  		
      var charts = [];
      
      $("#chartContainer").hide();
  		for(var i = 0; i < chartOptions.data.length; i++){
      		containerId = "chartContainer"+ i;
          
          if(document.getElementById(containerId) == null)
      				$('body').append('<div id='+ containerId + ' style="height: 370px; width: 100%;"></div>');
          else if(document.getElementById(containerId) !== null)
          		$("#"+containerId).show();
          
          charts[i] = new CanvasJS.Chart(containerId, {
          		title: {
              		text: chartOptions.title.text
              },
          		data: [chartOptions.data[i]]
          });
          chartOptions.data[i].type = chartType.options[chartType.selectedIndex].value;
          charts[i].render();
          chartOptions.rendered = true;
      }
  }
  else{
  		for(var i = 0; i < chartOptions.data.length; i++){
      		containerId = "chartContainer" + i;
          $("#"+containerId).hide();
      }
  		
     ...