Chartjs-How can I add user inputted values to my chart.js line graph?

0👍

I’ve found a few things:

  1. You have a typo in the html code. You have id="YValue" instead of id="yValue".

  2. You put .val and it should be .val().

  3. xValue and yValue vars have to be numbers, not strings.

  4. When you add the new data to the dataset, it has to be an object.

Putting Everything together…

HTML:

<div class="chart-container">
  <canvas id="myChart" width="400" height="400"></canvas>
</div>

<input type="number" name="xValue" placeholder="X Value" id="xValue" />
<input type="number" name="yValue" placeholder="Y Value" id="yValue" />
<input type="submit" id="update" value="Update" />

JQUERY:

$('#update').click(function() {

    var xValue = parseFloat($('#xValue').val());
    var yValue = parseFloat($('#yValue').val());

    myChart.data.datasets[0].data.push({ x: xValue, y: yValue });
    myChart.update();
});

Here you have a fiddle example… https://fiddle.jshell.net/rigobauer/ztsafu8w/

Leave a comment