Skip to content
Advertisement

Chart.js 2.7.2- Multiline get point value onClick

I would like to get value foreach point value. Don’t work because when I click on point I obtain only of the first line value. GetElementsAtEvent give me an array of 3 element (element active) but how I can get the clicked value?

This the Complete code.

    $(document).on("click", "#canvas", function(event){
            var activePoints = ctx.getElementsAtEvent(event);
        if(activePoints.length > 0){

                var clickedDatasetIndex = activePoints[0]._datasetIndex;
                var clickedElementindex = activePoints[0]._index;
                var label = ctx.data.labels[clickedElementindex];
                var value = ctx.data.datasets[clickedDatasetIndex].data[clickedElementindex]["y"];  

                alert("Clicked: " + label + " - " + value);    
        }
    });

Thanks

Advertisement

Answer

To get the exact element, use ctx.getElementAtEvent.

$(document).on("click", "#canvas", function(event){
    var activePoint = ctx.getElementAtEvent(event);
        
    if (activePoint.length > 0) {
       var clickedDatasetIndex = activePoints[0]._datasetIndex;
       var clickedElementIndex = activePoints[0]._index;
       var clickedDatasetPoint = ctx.data.datasets[clickedDatasetIndex];
       var label = clickedDatasetPoint.label;
       var value = clickedDatasetPoint.data[clickedElementIndex]["y"];  

       alert("Clicked: " + label + " - " + value);    
    }
});
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement