Chartjs-How to reduce list chart to one and use select dropdown to show selection without refresh page?

0👍

You can first generate options with axe and i values then whenever any option is selected get that index value and use JSON.parse(trend_axe[el]) this will give the JSON Array at that index and simply generate your chart . Also , i have use only one chart container so you need to destroy previous chart then redraw new chart on same container.

Demo Code :

var trend_axe = ['[{"axe":"MDVS1","date_":"2021-06-28","stock":0},{"axe":"MDVS1","date_":"2021-06-21","stock":1},{"axe":"MDVS1","date_":"2021-06-22","stock":3}]',
  '[{"axe":"MDV03","date_":"2021-06-18","stock":2},{"axe":"MDV03","date_":"2021-06-21","stock":1},{"axe":"MDV03","date_":"2021-06-23","stock":3}]',
  '[{"axe":"MDV02","date_":"2020-11-28","stock":3},{"axe":"MDV02","date_":"2020-11-30","stock":2}]',
  '[{"axe":"MDV04","date_":"2021-01-21","stock":3},{"axe":"MDV04","date_":"2020-10-14","stock":1}]'
] // {{trend_axe | safe}}
//generate option using json from server
var html = `<option value="">Select</option>`
for (i in trend_axe) {
  var item = JSON.parse(trend_axe[i]);
  //set value as index...[{}]
  html += `<option value="${i}">${item[0].axe}</option>`
};
document.getElementById("all_data").innerHTML = html
var chart;

function generate_chart(el) {
  if (chart) {
    chart.destroy(); //destroy previous chart
  }
  //not first option
  if (el != "") {
    var item = JSON.parse(trend_axe[el]);
    var label = [];
    for (j in item) {
      label.push(item[j].date_);

    }
    var stock = [];
    for (k in item) {
      stock.push(item[k].stock);

    }
    //generate chart
    chart = new Chart(document.getElementById("chart"), {
      type: 'line',
      data: {
        labels: label,
        datasets: [{
          label: 'Trend journalier des ventes',
          data: stock,
          fill: false,
          borderColor: '#0E9036',
          tension: 0.1

        }]
      },
    });

  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.0/chart.min.js" integrity="sha512-JxJpoAvmomz0MbIgw9mx+zZJLEvC6hIgQ6NcpFhVmbK1Uh5WynnRTTSGv3BTZMNBpPbocmdSJfldgV5lVnPtIw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<select id="all_data" onchange="generate_chart(this.value)"></select>
<canvas id="chart"></canvas>

Leave a comment