[Chartjs]-How to update Chart.js based on dropdown list?

1👍

When the selected options changes, you must not destroy the chart. All you need to do is performing the following steps.

  1. Change the data.labels
  2. Change the data of the unique dataset
  3. Update the chart itself

This is basically done as follows.

myChart.data.labels = <new labels>;
myChart.data.datasets[0].data = <new values>;
myChart.update();

The following example illustrates how this can be done in JavaScript.

orders = [
  { name: 'Luis', orders_by_user: '2' },
  { name: 'Jose', orders_by_user: '1' },
  { name: 'Miguel', orders_by_user: '3' }
];

const myChart = new Chart(document.getElementById('orders'), {
  type: 'bar',
  data: {
    labels: orders.map(o => o.name),
    datasets: [{
      label: 'Terminadas',
      data: orders.map(o => o.orders_by_user),
      borderColor: 'rgba(75, 192, 192, 1)',
      backgroundColor: "#229954",
      borderWidth: 1,
      yAxisID: 'Ordenes',
      xAxisID: 'Operarios',
    }]
  },
  options: {
    scales: {
      yAxes: [{
        id: "Ordenes",
        ticks: {
          beginAtZero: true,
          stepSize: 1
        },
        scaleLabel: {
          display: true,
          labelString: 'Ordenes'
        }
      }],
      xAxes: [{
        id: "Operarios",
        scaleLabel: {
          display: true,
          labelString: 'Operarios'
        }

      }],
    },
    title: {
      display: true,
      text: "Ordenes en estado terminado"
    },
    legend: {
      display: true,
      position: 'bottom',
      labels: {
        fontColor: "#17202A",
      }
    },
  }
});

orders.forEach(o => {
  const opt = document.createElement('option');
  opt.value = o.name;
  opt.appendChild(document.createTextNode(o.name));
  document.getElementById('operator').appendChild(opt);
});

function refreshChart(name) {
  myChart.data.labels = [name];
  if (name == 'All') {
     myChart.data.labels = orders.map(o => o.name),
     myChart.data.datasets[0].data = orders.map(o => o.orders_by_user);
  } else {
    myChart.data.labels = [name];
    myChart.data.datasets[0].data = orders.find(o => o.name == name).orders_by_user;
  }
  myChart.update();
}
Operarios:
<select id="operator" onchange="refreshChart(this.value)">
    <option>All</option>                                                            
</select> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="orders" height="90"></canvas>

Leave a comment