Changing Chart Type from Dropdown with data from external JSON - CanvasJS JavaScript Charts

Changing Chart Type from Dropdown with data from external JSON - 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 id="chartContainer" style="height: 370px; width: 100%;"></div>

<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>

JavaScript

var dataPoints = [];

var chart = new CanvasJS.Chart("chartContainer", {
	animationEnabled: true,
	theme: "light2",
	title: {
		text: "Daily Sales Data"
	},
	axisY: {
		title: "Units",
		titleFontSize: 24
	},
	data: [{
		type: "column",
		yValueFormatString: "#,### Units",
		dataPoints: dataPoints
	}]
});

function addData(data) {
	for (var i = 0; i < data.length; i++) {
		dataPoints.push({
			x: new Date(data[i].date),
			y: data[i].units
		});
	}
	chart.render();

}

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


var chartType = document.getElementById('chartType');
chartType.addEventListener( "change",  function(){
  chart.options.data[0].type = chartType.options[chartType.selectedIndex].value;
  chart.render();
});