Chart with user input data and parsing from array - CanvasJS JavaScript Charts

Chart with user input data and parsing from array - CanvasJS JavaScript Charts

by Amir Danish

HTML

<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<br/>
<!-- Just so that JSFiddle's Result label doesn't overlap the Chart -->
<div id="chartContainer" style="height: 360px; width: 100%;"></div>

Dtae: <input id = "dateValue" type= "date"/>
Y: <input id = "yValue"/ type = "number">
<input id = "button" type = "button" value= "Add">

JavaScript

var dateArray = [new Date(2016, 1, 1), new Date(2016, 1, 2), new Date(2016, 1, 3), new Date(2016, 1, 4), new Date(2016, 1, 5), new Date(2016, 1, 6), new Date(2016, 1, 7), new Date(2016, 1, 8), new Date(2016, 1, 9), new Date(2016, 1, 10), new Date(2016, 1, 11), new Date(2016, 1, 12), new Date(2016, 1, 13), new Date(2016, 1, 14), new Date(2016, 1, 15), new Date(2016, 1, 16), new Date(2016, 1, 17), new Date(2016, 1, 18)];

var numberArray = [10, 13, 18, 20, 17, 10, 13, 18, 20, 17, 20, 17, 10, 13, 18, 10, 13, 18];

var dps = []; //dataPoints. 

var chart = new CanvasJS.Chart("chartContainer", {
  title: {
    text: "Data Plotted from Array"
  },
  axisX: {
    title: "Axis X Title"
  },
  axisY: {
    title: "Units"
  },
  data: [{
    type: "line",
    dataPoints: dps
  }]
});


function parseDataPoints() {
  for (var i = dps.length; i < dateArray.length; i++)
    dps.push({
      x: new Date(dateArray[i]),
      y: numberArray[i]
    });
};

function addDataPoints(){
  parseDataPoints();
  chart.options.data[0].dataPoints = dps;
  chart.render();
}

addDataPoints();


//Taking user input and adding it to dataPoint
document.getElementById("button").onclick = function(){
  dateArray.push(new Date(document.getElementById("dateValue").value));
  numberArray.push(Number(document.getElementById("yValue").value));
  //Call your algorithm here
}