Lorenzo Alinovi
Lorenzo Alinovi

Reputation: 15

Can't update chart

why isn't the chart being updated with this code?:

<script type="text/javascript">
function updateConfigByMutating() {
    chart.options.plugins.title.text = 'new title';
    chart.update();
}
</script>

<input type="button" onclick="updateConfigByMutating(barChart)">

<body>
    <canvas id="barChart"></canvas>
    <script>
var ctxB = document.getElementById("barChart").getContext('2d');
var barChart = new Chart(ctxB, {
type: 'bar',
data: {
labels: ["Pennetta", "Menna", "Carinci", "Notaro", "Giangiacomo", "Carugno"],
datasets: [{
label: 'Andamento dei Voti - Elezioni 2021',
data: [<?php echo $checkpennetta[0]; ?>, <?php echo $checkmenna[0]; ?>, <?php echo $checkcarinci[0]; ?>, <?php echo $checknotaro[0]; ?>, <?php echo $checkgiangiacomo[0]; ?>, <?php echo $checkcarugno[0]; ?>],
backgroundColor: [
'rgba(250, 216, 89, 0.2)',
'rgba(207, 0, 15, 0.2)',
'rgba(232, 126, 4, 0.2)',
'rgba(31, 58, 147, 0.2)',
'rgba(137, 196, 244, 0.2)',
'rgba(77, 175, 124, 0.2)'
],
borderColor: [
'rgba(250, 216, 89, 1)',
'rgba(207, 0, 15, 1)',
'rgba(232, 126, 4, 1)',
'rgba(31, 58, 147, 1)',
'rgba(137, 196, 244, 1)',
'rgba(77, 175, 124, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
    </script>
</body>

I press the button and it does not update. The title doesn't change, and I don't know why, honestly

Thank you

....................................................................................................................................................................................................

Upvotes: 0

Views: 577

Answers (1)

uminder
uminder

Reputation: 26150

Remember that you assigned the newly created chart to the variable barChart. Therefore, try to change your updateConfigByMutating from...

function updateConfigByMutating() {
  chart.options.plugins.title.text = 'new title';
  chart.update();
}

...to

function updateConfigByMutating() {
  barChart.options.plugins.title.text = 'new title';
  barChart.update();
}

Upvotes: 2

Related Questions