Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get yLabel value onclick chart js

I want to have the y label value, when I click on the bar.

<code>barImage</code>

Like the above example, when I click on feb blue bar I want to have label value, which is 40

I looked for examples on stackOverFlow and other sites but they only have example of label for the legend show up.

some of the code I tried

onClick: function(evt, element) {
      var activePoints = bar_chart.getElementAtEvent(evt);
      console.log(activePoints[0]._model.datasetLabel);
}
like image 717
Amer Bearat Avatar asked May 24 '18 18:05

Amer Bearat


2 Answers

This demo gives the value in the bar chart when you click on it. I'm not a chart.js expert so there may be better solutions.

https://codepen.io/newschapmj1/pen/PerOzM

/* from https://github.com/chartjs/Chart.js/issues/2292 */
document.getElementById("myChart").onclick = function (evt) {
        var activePoints = myChart.getElementsAtEventForMode(evt, 'point', myChart.options);
        var firstPoint = activePoints[0];
        var label = myChart.data.labels[firstPoint._index];
        var value = myChart.data.datasets[firstPoint._datasetIndex].data[firstPoint._index];
        alert(label + ": " + value);
    };
like image 183
JohnC Avatar answered Nov 14 '22 23:11

JohnC


Chart.js version = 3.2.1

From the official documentation:

onClick: (evt) => {
    const points = myChart.getElementsAtEventForMode(evt, 'nearest', { intersect: true }, true);

    if (points.length) {
        const firstPoint = points[0];
        var label = myChart.data.labels[firstPoint.index];
        var value = myChart.data.datasets[firstPoint.datasetIndex].data[firstPoint.index];
        alert(label +" : "+ value);
    }
}
like image 20
Mrunalraj Redij Avatar answered Nov 15 '22 00:11

Mrunalraj Redij