Chartjs-How to get a value from function javascript and print it to the chart

0๐Ÿ‘

โœ…

As this doc-side states you have to use an array of data points (numbers), but within your data the first item is not a number:

data: [<span id='akurasi'></span>,100]

You can query this value by using getElementById for instance:

data: [+document.getElementById("akurasi").innerText,100]

It should work if your calcError function returns a numeric value to show it with akurasi:

<span id='akurasi'>35</span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>
  <title>Hello!</title>
</head>

<body>

<canvas id="chart" width="100" height="100"></canvas>
<span id='akurasi'></span>

</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.js"></script>

<script type="text/javascript">

 $(document).ready(function(){
           // ...
           document.getElementById("akurasi").innerText = 35;
           
           var chart = setupChart();
           // you can do whatever you want with this chart here...
           
 });

 function setupChart(){

    return new Chart(document.getElementById("chart"), {
        type: 'polarArea',
        data: {
          labels: ["Data Training (%)", "Data Testing (%)"],
          datasets: [
            {
              label: "jumlah ",
              backgroundColor: ["#3e95cd", "#ff4137"],
              data: [+document.getElementById("akurasi").innerText,100]
            }
          ]
        },
        options: {
          legend: { display: false },
          title: {
            display: true,
            text: 'Data Training'
          }
        }
    });

 }

</script>
</html>

Hope this helps.

Leave a comment