I am creating a data dashboard and I have stumbled on a problem that has me completely stumped. I am using chart.js as the chart renderer and jquery/js for the control of the dashboard. I want a user to be able to add a new chart via a button click, I can render the html content easily using the following:
$('.graphs').append('<canvas id="' + name + '" data-dataset="2323"></canvas>');
This is creates the html as required, however chart.js requires a chunk of javascript per graph for the options and the dataset. I have no idea how to create this element of the application, I cant find any documentation that supports this method of dynamic graph creation. I am reasonably proficient at jquery, but this has me scratching my head.
I am looking for a method on how to create this code dynamically:
new Chart(document.getElementById(name), {
type: 'bar',
data: {
labels: ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"],
datasets: [{
label: "Sales (millions)",
backgroundColor: ["#3e95cd"],
data: datasets1
}]
},
options: {
legend: {
display: false
},
title: {
display: false,
text: 'Example Bar Chart'
},
scales: {
xAxes: [{
gridLines: {
display: false
}
}],
yAxes: [{
gridLines: {
display: true
}
}]
}
},
});
Or some other approach.