I want to dynamically create a CanvasJS chart depending on N amount of objects from a JSON array. If a JSON array has 3 objects, the web page should be able to display 3 charts.
<div class="container-fluid" id="spectraContainers">
</div>
Through the id "spectraContainers", I have a javascript function that dynamically creates a new div with a unique id. In that same function, a new chart is created with its unique id.
document.getElementById("chartContainers").innerHTML += '<div class="row"> <div id="chart_container_' + chartNumber + '" style="width: 100 %; height: 500px; ">Container </div></div>';
...
...
...
var chartContainerID = "chartcontainer_" + chartNumber;
var chart = new CanvasJS.Chart(chartContainerID, {
animationEnabled: true,
zoomEnabled: true,
theme: "light2",
title: {
text: chartTitle,
},
axisX: {
title: "x axis label",
gridDashType: "dash",
gridThickness: 2
},
axisY: {
title: "y axis label",
gridDashType: "dash",
gridThickness: 2
},
dataPointMaxWidth: 20,
dataPointWidth: 10,
data: [{
type: "column",
dataPoints: points
}]
});
chart.render();
I've verified that all values are valid. It seems like only ONE canvasJS chart (the third object from the json array) can be rendered in a page within this function. If I were to specifically generate a chart for index 0 or 1 in the json array, the specified index for the chart will be rendered.
I know it's possible to render multiple canvasJs charts by manually creating a new chart variable for each uniqueID. However, I would like to dynamically generate N-amount of charts. I am pretty new to javascript and would appreciate any advice!!
Using innerHTML replaces the contents of div element rather than appending child element. Try using append method.