Skip to content Skip to sidebar Skip to footer

Show Google Chart On Button Click

I have the following div on a page where I would like a google chart to load on a button click: html:

Solution 1:

when using the promise returned from the load statement, the callback is not needed...

change the load statement as follows...

    google.charts.load('current', {
      packages: ['corechart'],
    }).then(function() {

also need to ensure the library is included...

<scriptsrc="https://www.gstatic.com/charts/loader.js"></script>

EDIT

note: the following library is old and should no longer be used, you can remove it. <script src="https://www.google.com/jsapi"></script> see the release notes for more info...


the load statement will wait for the document to load, no need for --> $(document).ready

recommend loading google first, then wait for the button click...

see following working snippet...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  $(".btn").click(function() {
    var jsonData = {"Battery Voltage, (V)":{"2017-10-09T00:00:00.000Z":12.5,"2017-10-09T00:01:00.000Z":12.44,"2017-10-09T00:02:00.000Z":12.43}};

    var chartData = [];
    Object.keys(jsonData).forEach(function (column) {
    chartData.push(['Datetime', column]);
    Object.keys(jsonData[column]).forEach(function (dateValue) {
      chartData.push([newDate(dateValue), jsonData[column][dateValue]]);
    });
    });
    var data = google.visualization.arrayToDataTable(chartData);

    var options = {
      chartArea: {width:'90%', height:'65%'},
      title: 'Battery Voltage',
      curveType: 'function',
      legend: { position: 'bottom' }
    };

    var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
    chart.draw(data, options);
  });
});
<scriptsrc="https://www.gstatic.com/charts/loader.js"></script><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script><inputclass="btn"type="button"value="Draw Chart" /><divid="line_chart"></div>

Solution 2:

Add <script type="text/javascript" src="https://www.google.com/jsapi"> to the head of your html page to load the library for the chart

Solution 3:

Maybe you forgot to import all the necessary files. Make sure you are importing the jquery cdn (or download the file to your server)

<scriptsrc="https://code.jquery.com/jquery-3.2.1.min.js"></script>

and google chart cdn

<scriptsrc="https://www.google.com/jsapi"></script>

and check if you need an API key to use the plugin.

Post a Comment for "Show Google Chart On Button Click"