Search code examples
javascripthtmlcanvasjs

How to get javascript var data from html element? (working with canvasjs)


I am trying to make a chart with CanvasJS. Here is my HTML:

<div id="chartContainer" style="height: 360px; width: 100%;"></div>
<div id="test1">100</div>
<div id="test2">110</div>

and my JS is

var dataPoint1 = document.getElementById("test1");
var dataPoint2 = document.getElementById("test2");

var chart = new CanvasJS.Chart("chartContainer",
{  
  data: [
  {
    type: "column",
    dataPoints: [
        { label: "Apple", y: dataPoint1},
        { label: "Mango", y: dataPoint2}
    ]
  }
  ]
});

chart.render();

See my fiddle here: the chart is not correctly rendered.


Solution

  • You need to add innerHTML in order to access the content in the DOM element. Also, you need to then apply parseInt to parse the string in and return an integer.

    var dataPoint1 = document.getElementById("test1").innerHTML;
    var dataPoint2 = document.getElementById("test2").innerHTML;
    

    see your updated jsfiddle here

    In your original code you were setting the variables to the whole element, but not the value in the element. You should always use console.log and then you can see in the console the result you are getting. It is also useful to check typeof what is in the element, as this would have helped you see that it was returning a String as opposed to a Number.

    i.e console.log(dataPoint1) -- Originally this was returning <div id="test1">10</div> which would have helped you realise you need to get the value in the div, as opposed to the entire element.

    var dataPoint1 = document.getElementById("test1").innerHTML;
    var dataPoint2 = document.getElementById("test2").innerHTML;
    
    var chart = new CanvasJS.Chart("chartContainer",
    	{  
          data: [
          {
            type: "column",
            dataPoints: [
                { label: "Apple", y: parseInt(dataPoint1)},
                { label: "Mango", y: parseInt(dataPoint2)}
            ]
          }
          ]
        });
    
     chart.render();
    <script src="https://cdnjs.cloudflare.com/ajax/libs/canvasjs/1.7.0/canvasjs.min.js"></script>
    <div id="chartContainer" style="height: 360px; width: 100%;"></div>
    <div id="test1">10</div>
    <div id="test2">12</div>