[Chartjs]-Append suffix to Chart.js dataset?

1πŸ‘

βœ…

To make this work you can use the callback of the tooltips configuration to append a string to the value in the dataset, something like this:

var containers = document.querySelectorAll('.chart');
containers.forEach(function(container) {
  var charts = JSON.parse(container.dataset.charts);

  var div = document.createElement('div');
  div.classList.add('chart-container');

  var canvas = document.createElement('canvas');
  div.appendChild(canvas);
  container.appendChild(div);

  var ctx = canvas.getContext('2d');
  var config = charts;
  var myChart = new Chart(ctx, $.extend(config, {
    options: {
      tooltips: {
        enabled: true,
        mode: 'single',
        callbacks: {
          label: function(tooltipItems, data) {
            return data.datasets[0].data[tooltipItems.index] + 'g';
          }
        }
      }
    }
  }));
});
canvas {
  background-color: #eee;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"></script>
<div class="chart" data-charts='{"type":"doughnut","data":{"labels":["Label1","Label2","Label3"],"datasets":[{"data":["56","31","21"]}]}}'></div>

Leave a comment