Thomas Williams Thomas Williams - 11 months ago 85
Javascript Question

Send data to google chart function

I have 3 google charts which are identical apart from the data and id of the chart.
At the moment I call these charts like this.


Because the charts are almost identical I would like one function instead of 3, as I like to use less code if possible, but when I do this it doesn't work.

If I could send the data like this, then I wouldn't need 3 functions, I would only need one drawBasic function, with different data every time it is called.
I won't paste all 3 functions I will just paste the one function to show how my function is laid out.

function drawBasic() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Month');
data.addColumn('number', 'Sales');

[new Date(2016, 4), 0],[new Date(2016, 5), 0],[new Date(2016, 6), 0],[new Date(2016, 7), 0],[new Date(2016, 8), 0],[new Date(2016, 9), 0]

var options = {
title: 'Total Sales Last Six Months',
hAxis: {
title: 'Sales'
vAxis: {
title: 'Month'
backgroundColor: { fill:'transparent' },
legend: {position: 'none'},
var chart = new google.visualization.BarChart(document.getElementById('total_sales_chart'));

chart.draw(data, options);

chart.draw(data, options);

So is it possible for me to send my data to the function. I am new to google charts, but where possible I don't like using 3 functions when I can get away with only one.

Answer Source

setOnLoadCallback is meant to be used once per page load

however, you can add the callback to the load statement

then call the draw function from there...

google.charts.load('current', {
  callback: function () {
    drawBasic(mydata1, myid1);
    drawBasic(mydata2, myid2);

    function drawBasic(data, id) {
  packages: ['corechart']