0

I have successfully displayed the value, but why is only one value displayed? I want the value in sequence

This my code

/*my datasets code*/
datasets: [{
  label: 'Daily Data',
  data: [730000, 1012000, 1220000, 1831000, 560000, 2012000, 890000],
  borderColor: '#3f89fb',
  borderWidth: 3,
  fill: false
}]

/*my tooltips code*/
tooltips: {
  callbacks: {
    label: function(tooltipItem, chart) {
      for (var i = 0; i < chart.datasets[0].data.length; i++) {
        return chart.datasets[0].data[i] / 1e6 + 'M';
      }
    }
  }
}

and this my result, all day value is 0.73M enter image description here

3 Answers 3

2

Look in the Tooltip Item Documentation.

In your case tooltipItem.index contains the index of this data item in the dataset. So you can return the value doing so:

function(tooltipItem, chart) {
    return chart.datasets[0].data[tooltipItem.index] / 1e6 + 'M';
}

And here is the demo:

var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: 'Daily Data',
            data: [730000, 1012000, 1220000, 1831000, 560000, 2012000, 890000],
            borderColor: '#3f89fb',
            borderWidth: 3,
            fill: false
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        },
        tooltips: {
            callbacks: {
                label: function(tooltipItem, chart) {
                    return chart.datasets[0].data[tooltipItem.index] / 1e6 + 'M';
                }
            }
        }
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>

Sign up to request clarification or add additional context in comments.

1 Comment

so great, sorry I didn't read the documentation in detail, btw thank you for helping me
0

Instead of return inside for loop which will exit the loop, you can save your results somewhere like below

var result = []
for (var i = 0; i < chart.datasets[0].data.length; i++) {
        result.push(chart.datasets[0].data[i] / 1e6 + 'M');
      }

Comments

0

This is because return stops execution and exits the function. return always exits its function immediately, with no further execution if it's inside a loop.

See this answer: Does return stop a loop?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.