Declare data value dynamicaly to chart js

๐Ÿ‘:0

When creating the chart, you need to assign it to a constant that can be referenced later on when updating the values of its dataset.

const chart = new Chart(...

Then you could define an input element where the user would enter individual values separated by a space each. A button element would trigger the addValues function upon a mouse click.

<input id="chart1"><button type="button" onClick="addValues()">

The addValues function would split the values from the input element and convert them to numbers to finally assign them to the data of the unique dataset. Then it needs to invoke chart.update().

function addValues() {
  var values = document.getElementById("chart1").value;
  chart.data.datasets[0].data = values.split(/\s+/).map(v => Number(v));
  chart.update();
}

Please have a look at the following runnable code snippet to see how it works.

function addValues() {
  var values = document.getElementById("chart1").value;
  chart.data.datasets[0].data = values.split(/\s+/).map(v => Number(v));
  chart.update();
}

const chart = new Chart('line-chart', {
  type: 'line',
  data: {
    labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
    datasets: [{
      label: 'Total Collection',
      backgroundColor: 'blue',
      borderColor: 'blue',
      data: [],
      fill: false,
    }]
  }
});
input {
  width: 400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
Values: <input id="chart1"><button type="button" onClick="addValues()">Add Values</button>
<canvas id="line-chart" height="80"></canvas>

Leave a comment