[Chartjs]-Switch chart.js data with button click

10👍

That could be accomplished by replacing the data and labels array on button click …

$("#0").click(function() {
    var data = forecast_chart.config.data;
    data.datasets[0].data = temp_dataset;
    data.datasets[1].data = rain_dataset;
    data.labels = chart_labels;
    forecast_chart.update();
});

$("#1").click(function() {
    var chart_labels = ['00:00', '03:00', '06:00', '09:00', '12:00', '15:00', '18:00', '21:00'];
    var temp_dataset = ['5', '3', '4', '8', '10', '11', '10', '9'];
    var rain_dataset = ['0', '0', '1', '4', '19', '19', '7', '2'];

    var data = forecast_chart.config.data;
    data.datasets[0].data = temp_dataset;
    data.datasets[1].data = rain_dataset;
    data.labels = chart_labels;
    forecast_chart.update();
});

Here’s the working fiddle

Leave a comment