[Chartjs]-How to add labels into the chart.js?

1👍

I think you are adding javascript in <style> element.

For datalabels, you must register the plugin, see https://stackoverflow.com/a/75996303/2057925

1👍

So yeah it worked thank you there is my code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Chart.js Example</title>
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.0.0"></script>
  <style>
    .chartjs-title {
      font-family: Roboto;
    }

    #inputValue {
      width: 200px;
      height: 100px;
      font-size: 20px;
    }

    #inputContainer {
      display: flex;
      justify-content: center;
      align-items: center;
    }
  </style>
</head>
<body>
  <div>
    <canvas id="myChart" style="background-color: transparent;"></canvas>
    <div id="inputContainer">
      <input type="number" id="inputValue" min="0" placeholder="Wprowadź liczbę">
    </div>
  </div>

  <script>
    // Register the plugin to the Chart.js library
    Chart.register(ChartDataLabels);

    const ctx = document.getElementById('myChart');

    const chart = new Chart(ctx, {
      type: 'bar',
      data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [{
          data: [12, 19, 3, 5, 2, 3],
          borderWidth: 1
        }]
      },
      options: {
        plugins: {
          datalabels: {
            color: 'white',
            anchor: 'end',
            align: 'start',
            offset: -6,
            font: {
              weight: 'bold',
              size: '14'
            },
            formatter: function(value, context) {
              return value.toLocaleString('pl-PL', {style: 'currency', currency: 'PLN'}).replace('PLN', 'zł');
            }
          }
        },
        indexAxis: 'y',
        scales: {
          x: {
            ticks: {
              fontFamily: 'Roboto',
              callback: function(value, index, values) {
                return value.toLocaleString('pl-PL', {style: 'currency', currency: 'PLN'}).replace('PLN', 'zł');
              }
            },
            grid: {
              display: false
            }
          },
          y: {
            ticks: {
              fontFamily: 'Roboto',
              anchor: 'end'
            },
            grid: {
              display: false
            }
          }
        }
      }
    });

    const input = document.getElementById('inputValue');
    input.addEventListener('input', () => {
      chart.data.datasets[0].data = [
        input.value * 0.8 + 10,
        input.value * 0.9 + 10,
        input.value * 2 + 10,
        input.value * 3 + 10,
        input.value * 4 + 10,
        input.value * 10 + 10
      ];
      chart.update();
    });
  </script>
</body>
</html>

Leave a comment