[Chartjs]-Chartsjs update datasets with dropdown

2👍

Use this good Tutorial:
chart.js Tutorial (And change your code to the chart.js way)

the only thing when a change event is fired via dropdown change, you must call

chart.update()

to make your changes into the chart object to be rendered into the HTML.

7👍

Hello world (Most basic example) below

The “solution” for this Q by Vitelli is not really an answer for other users (No code example, no snippet, no extra details).

The idea –> On click change data to index (0 show the zero-index data of the array).

<button class="btn active" onclick="changeData(0)">Datasets 1</button>
/* js*/
dataset.label = dataObjects[index].label; /* change label value */

And run update():
https://www.chartjs.org/docs/latest/developers/updates.html

The changeData function gets index parameter. Very easy to change this code to select menu (Get the index of select menu on change):
https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/selectedIndex

Snippet

var dataObjects = [
  {
    label: "Datasets 1",
    data: [8, 6, 4]
  },
  {
    label: "Datasets 2",
    data: [3, 5, 7]
  },
  {
    label: "Datasets 3",
    data: [11, 8, 12]
  }
]

/* data */
var data = {
  labels: ["Africa", "Asia", "Europe"],
  datasets: [  {
    label:  dataObjects[0].label,
    data: dataObjects[0].data,
    /* global setting */
    backgroundColor: [
      'rgba(255, 99, 132, 0.2)',
      'rgba(54, 162, 235, 0.2)',
      'rgba(255, 206, 86, 0.2)'
    ],
    borderColor: [
      'rgba(255, 99, 132, 1)',
      'rgba(54, 162, 235, 1)',
      'rgba(255, 206, 86, 1)'
    ],
    borderWidth: 1
  }]
};

var options = {
  legend: {
    display: true,
    fillStyle: "red",
    
    labels: {
      boxWidth: 0,
      fontSize: 24,
      fontColor: "black",
    }
  },
  scales: {
    xAxes: [{
      stacked: false,
      scaleLabel: {
        display: true,
        labelString: 'Country'
      },
    }],
    yAxes: [{
      stacked: true,
      scaleLabel: {
        display: true,
        labelString: 'Millions'
      },
      ticks: {
        suggestedMin: 0,
        suggestedMax: 10
      }
    }]
  },/*end scales */
  plugins: {
    // datalabels plugin
    /*https://chartjs-plugin-datalabels.netlify.com*/
    datalabels: {
      color: 'black',
      font:{
        size: 25
      }
    }
  }
};

var chart = new Chart('chart-0', {
  plugins: [ChartDataLabels], /*https://chartjs-plugin-datalabels.netlify.com*/
  type: 'bar',
  data: data,
  options: options
});

function changeData(index) {
  chart.data.datasets.forEach(function(dataset) {
    dataset.label = dataObjects[index].label;
    dataset.data = dataObjects[index].data;
    //dataset.backgroundColor = dataObjects[index].backgroundColor;
  });
  chart.update();
}

/* add active class on click */
// Add active class to the current button (highlight it)
var header = document.getElementById("myDIV");
var btns = header.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
  btns[i].addEventListener("click", function() {
    var current = document.getElementsByClassName("active");
    current[0].className = current[0].className.replace(" active", "");
    this.className += " active";
  });
}
/* Style the buttons */
.btn {
  border: none;
  outline: none;
  padding: 10px 16px;
  background-color: #f1f1f1;
  cursor: pointer;
  font-size: 18px;
}

/* Style the active class, and buttons on mouse-over */
.active, .btn:hover {
  background-color: #1a73e8;
  color: white;
}
<div id="myDIV">
  <button class="btn active" onclick="changeData(0)">Datasets 1</button>
  <button class="btn" onclick="changeData(1)">Datasets 2</button>
  <button class="btn" onclick="changeData(2)">Datasets 3</button>
</div>
<canvas id="chart-0"></canvas>

<hr>


<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@0.7.0"></script>

Notes:

0👍

  var data = {
appleData : {
      label: 'apples',
      data: [12, 19, 3, 17, 6, 3, 7],
      backgroundColor: "rgba(153,255,51,0.6)"
},
orangeData : {
  label: 'oranges',
  data: [2, 29, 5, 5, 2, 3, 10],
  backgroundColor: "rgba(255,153,0,0.6)"
}
}

var ctx = document.getElementById('myChart').getContext('2d');
function updatechart() {
var e = document.getElementById("dd");
var dd = e.options[e.selectedIndex].value;
var fruitData = {
  labels: ['M', 'T', 'W', 'T', 'F', 'S', 'S'],
  datasets: [data[dd]] 
}
var myChart = new Chart(ctx, {
     type: 'line',
     data: fruitData
   });

  }

0👍

Html :

                                        <select class="form-control float-right " id="change_year" onchange="updateChart();" name="change_year" style="width:150px" required>
                                        <option value="2020">2020</option>
                                        <option value="2021" selected>2021</option>
                                    </select>

JS :

// Dummy Data for Year 2020 and 2021
var data = {
2020: {
    label: 'In this Month',
    backgroundColor: "rgba(0, 97, 242, 1)",
    hoverBackgroundColor: "rgba(0, 97, 242, 0.9)",
    borderColor: "#4e73df",
    data: [4215, 5812, 6251, 7841, 9821, 1484, 19000, 1020, 100, 3000, 5000, 1000]
},
2021: {
    label: 'In this Month',
    backgroundColor: "rgba(0, 97, 242, 1)",
    hoverBackgroundColor: "rgba(0, 97, 242, 0.9)",
    borderColor: "#4e73df",
    data: [4215, 5312, 6251, 7841, 9821, 14984, 19000, 1200, 15000, 5000, 6000, 20000]
}}



// Variable for Chart created Globally
var myBarChart;


function updateChart() {
var ctx = document.getElementById("yearlyBarChart");
var e = document.getElementById("change_year");
// Get the selected value of dropdown here
var dd = e.options[e.selectedIndex].value;
// Create dataset
var yearData = {
    labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
    datasets: [data[dd]]
}
// Clear you chart before assiging new dataset
if (myBarChart !== undefined) {
    myBarChart.clear();
    myBarChart.destroy();
}

myBarChart = new Chart(ctx, {
    type: "bar",
    data: {
        labels: yearData.labels, //set labels
        datasets: yearData.datasets // set data for selected year
    },
    options: {
        maintainAspectRatio: false,
        layout: {
            padding: {
                left: 10,
                right: 25,
                top: 25,
                bottom: 0
            }
        },
        scales: {
            xAxes: [{
                time: {
                    unit: "month"
                },
                gridLines: {
                    display: false,
                    drawBorder: false
                },
                ticks: {
                    maxTicksLimit: 10
                },
                maxBarThickness: 25
            }],
            yAxes: [{
                ticks: {
                    min: 0,
                    max: 20000,
                    maxTicksLimit: 5,
                    padding: 10,
                    // Include a dollar sign in the ticks
                    callback: function (value, index, values) {
                        return "$ " + number_format(value);
                    }
                },
                gridLines: {
                    color: "rgb(234, 236, 244)",
                    zeroLineColor: "rgb(234, 236, 244)",
                    drawBorder: false,
                    borderDash: [2],
                    zeroLineBorderDash: [2]
                }
            }]
        },
        legend: {
            display: false
        },
        tooltips: {
            titleMarginBottom: 10,
            titleFontColor: "#6e707e",
            titleFontSize: 14,
            backgroundColor: "rgb(255,255,255)",
            bodyFontColor: "#858796",
            borderColor: "#dddfeb",
            borderWidth: 1,
            xPadding: 15,
            yPadding: 15,
            displayColors: false,
            caretPadding: 10,
            callbacks: {
                label: function (tooltipItem, chart) {
                    var datasetLabel =
                        chart.datasets[tooltipItem.datasetIndex].label || "";
                    return datasetLabel + ": $ " + number_format(tooltipItem.yLabel);
                }
            }
        }
    }

});
// once you set new data, need to update the chart.
myBarChart.update();}

Leave a comment