[Chartjs]-Unable to display multiple line charts in javascript

1πŸ‘

βœ…

It seems like that when you add a new part to the inner html it has some weird behaviour with chart.js, if you first make all the divs with forms and canvasses and then create the charts it works fine:

var xValues = [50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150];
var yValues = [7, 8, 8, 9, 9, 9, 10, 11, 14, 14, 15];

function displayPanel(i) {
  var panel = document.getElementById('panel');
  panel.innerHTML += `
    <div class="row">
        <div class="column">
             <form>
                <label id="paramname_${i}" for="paramvalue">${i}</label>
                <input type="text" id="paramvalue_${i}" name="param" value=${i} readonly>  
              </form>
         </div>
         <div id="chart_${i}" class="column">
             <canvas id="myChart${i}" style="width:100%;max-width:600px"></canvas>
         </div>`;
}

function createChart(i) {
  new Chart("myChart" + i, {
    type: "line",
    data: {
      labels: xValues,
      datasets: [{
        fill: false,
        lineTension: 0,
        backgroundColor: "rgba(0,0,255,1.0)",
        borderColor: "rgba(0,0,255,0.1)",
        data: yValues
      }]
    },
    options: {
      legend: {
        display: false
      },
      scales: {
        yAxes: [{
          ticks: {
            min: 6,
            max: 16
          }
        }],
      }
    }
  });
}

function createUI(k) {
  for (i = 0; i < k; i++) {
    displayPanel(i);
  }

  for (i = 0; i < k; i++) {
    createChart(i);
  }
}

createUI(3)
<style>.column {
  float: left;
  align-self: right;
  width: 50%;
  padding: 10px;
}

.row {
  content: "";
  clear: both;
  display: table;
}

</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
<!DOCTYPE html>
<html>

<body>
  <div id="panel"></div>
</body>

Leave a comment