Diego
Diego

Reputation: 159

Can't get if else statement in tooltip label to work in chartjs

i'm using chartjs. In chartjs I'm using custom tooltips with the code below. The problem I encounter is that the if-statement returns all labels except the last one. The last one + the total sum of the labels are returned in the else-statement.

The problem is that this way when I click on a the last label in a rendered chart (to remove the data), I also remove the total from the tooltip. I have tried to change the .length -1 in the if statement to just .length. This way the last label gets included in the if-statement, but the total label doesn't work anymore. Probably because the else-statement doesn't get executed anymore. I'm really stuck and hope someone can help.

tooltips: {
        mode: 'index',         
        titleFontSize: 14,
        callbacks: {
            label: function(tooltipItem, data) {
                var corporation = data.datasets[tooltipItem.datasetIndex].label;
                var valor = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
                var total = 0;
                for (var i = 0; i < data.datasets.length; i++)
                    total += data.datasets[i].data[tooltipItem.index];
                if (tooltipItem.datasetIndex != data.datasets.length - 1) {
                    return corporation  + " €" + valor.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
                } else {                        
                    return [corporation  + " €" + valor.toString().replace(/\B(?=(\d{3})+(?!\d))/g, "."), "Inschrijfprijs : €" + total.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".")];
                }

            }                

        }
    }

Upvotes: 0

Views: 519

Answers (1)

uminder
uminder

Reputation: 26150

In the else case you return an array but you should return a string. Remove the angle brackets and check if it works.

} else {                        
  return corporation  + " €" + valor.toString().replace(/\B(?=(\d{3})+(?!\d))/g, "."), "Inschrijfprijs : €" + total.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
}

Tooltip Callbacks from Chart.js documentation states

label (...) Returns text to render for an individual item in the tooltip.

Upvotes: 0

Related Questions