foojae foojae - 6 months ago 29
jQuery Question

Loading or Activating ChartJS on Load

I have Chart.js set up with a form so that it takes input fields from the form and after clicking Submit/Update button, it generates a donut chart using those numbers from the input fields as data points.

The issue is how can I get the form or Chart.js to run once and generate a donut chart with the input fields numbers when its on the page (on page load).

The form input fields are already filled with numbers/data via HTML5 Local Storage).

I've tried jQuery .submit(); on page load but nothing happens. I appreciate any help. Thank you.

EDIT: I've gone ahead and created a fiddle to re-create the issue.

$(document).ready(function () {

$("#submit-btn").click(function (e) {

e.preventDefault();

var outputyearly = $('#outputyearly');
var amount = parseInt($('#amount').val().replace(/,/g, ''), 10);
var rate = parseFloat($('#rate').val(), 10);
var term = parseFloat($('#term').val(), 10);

// Some math calculations code

if (window.onload.myDoughnutChart != null) {
window.onload.myDoughnutChart.destroy();
}

var ctx = document.getElementById("myChart").getContext("2d");

window.onload.myDoughnutChart = new Chart(ctx, {
type: 'doughnut',
data: data,
options: options
});

});

});

Answer

You can put the code that draws the chart in a function and call that function on both the $(document).ready and $("#submit-btn").click event, like this:

function drawChart() {
  var outputyearly = $('#outputyearly');
  var amount = parseInt($('#amount').val().replace(/,/g, ''), 10);
  var rate = parseFloat($('#rate').val(), 10);
  var term = parseFloat($('#term').val(), 10);

  //Destroy the dougnut chart here, not sure how it's accessible, but it won't work through window.onload

  var ctx = document.getElementById("myChart").getContext("2d");

  new Chart(ctx, {
      type: 'doughnut',
      data: data,
      options: options
  });
}

$(document).ready(function() {
  drawChart();
  $("#submit-btn").click(function (e) {
     e.preventDefault();
     drawChart();
   });
 });

Note that $(document).ready already imposes the code inside of it to be executed when the page is done, so putting a window.onload inside of it won't make any difference.