Chartjs-ChartJS: subsequent charts hide previous charts

0๐Ÿ‘

โœ…

I was able solve the issue using insertAdjacentHTML, checkout the following:

var res_chartArray = [];

function addChart() {
  var res_chartPicker = document.getElementById("res_chartPicker");
  /* Selection: Bar, Line, Pie */

  /*Apprends the div+canvas to the screen*/
  if (res_chartArray.length == 0)
    document.getElementById("res_div").innerHTML += "<div id='div_chart" + res_chartArray.length + "'>" + res_chartPicker.value + "<input type='button' value='delete' onclick='deleteChart(this)'><br><canvas id='chart" + res_chartArray.length + "'></div>";
  else
    document.getElementById("div_chart" + (res_chartArray.length - 1)).insertAdjacentHTML('afterend', "<div id='div_chart" + res_chartArray.length + "'>" + res_chartPicker.value + "<input type='button' value='delete' onclick='deleteChart(this)'><br><canvas id='chart" + res_chartArray.length + "'></div>");

  var cur_ctx = document.getElementById('chart' + (res_chartArray.length)).getContext('2d');

  res_chartArray.push(new Chart(cur_ctx, {
    type: res_chartPicker.value,
    data: {
      labels: ["test"],
      datasets: [{
        label: "test1",
        data: [20]
      }]
    },
    options: {
      title: {
        display: true,
        text: "Test"
      }
    }
  }));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<select onchange="addChart()" id="res_chartPicker">
  <option value="bar">Bar</option>
  <option value="line">Line</option>
  <option value="pie">Pie</option>
</select>
<div id="res_div">
</div>

Leave a comment