Chartjs-Chart.js โ€“ Getting data from HTML

1๐Ÿ‘

I see that there are some issue when you are fetching data from the HTML data attribute, the code $(this).attr("data-label") should be $(this).data("label") so it will give the value correctly.

There are some other improvements also that I have made in your code see the fiddle -> https://jsfiddle.net/pjr5wuft/3/ or the code below.

$(document).ready(function() {
  var barStyle = {
    scaleLineColor: "rgba(0,0,0,0)",
    scaleShowLabels: true,
    scaleShowGridLines: false,
    pointDot: false,
    datasetFill: false,
    // Sadly if you set scaleFontSize to 0, chartjs crashes
    // Instead we'll set it as small as possible and make it transparent
    scaleFontSize: 9,
  };

  $(".barchart").each(function() {
    //Get context with jQuery - using jQuery's .get() method.
    var ctx = $(this)
      .get(0)
      .getContext("2d");
    //This will get the first returned node in the jQuery collection.
    var myNewChart = new Chart(ctx);   
    // Get the chart data and convert it to an array
    var chartData = $(this).data("chart");

    // Build the data object
    var data = {};
    var labels = [];
    var datasets = {};

    // Create a null label for each value
    for (var i = 0; i < chartData.length; i++) {
      labels.push("");
    }

    // Create the dataset
    datasets["strokeColor"] = 'rgba(54, 162, 235, 0.2)';
    datasets["data"] = chartData;    

    // Add to data object
    data["labels"] = $(this).data("label");
    data["datasets"] = Array(datasets);

    new Chart(ctx).Bar(data, barStyle);
  });
});

Leave a comment