Steffen
Steffen

Reputation: 109

Chart.js: chart does not update

I'm using chart.cs to try a Chart. It works fine so far. Now I want change data dynamicly but the update() functin does not work. What do I wrong?

    <html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.min.js"></script>
</head>
<body>
<button onclick="changedata()">changedata</button> 
<canvas id="testChart"></canvas>
<script>
var testChart;
var test_labels = ['06:00', '06:10', '06:20', '06:30', '06:40', '06:50', '07:00'];
var test_data = ['1', '2', '3', '4', '3', '2', '1'];

var ctx = document.getElementById("testChart").getContext('2d');
testChart = new Chart(ctx, {
type: 'line',
data: {
    labels: test_labels,
    datasets: [{
        data: test_data,
        borderColor: "#ff0000",
        borderWidth: 1,
    }]
} 
});

function changedata(){
    test_data  = ['4', '3', '2', '1', '2', '3', '4'];
    testChart.update();
}
</script>
</body>
</html>

Upvotes: 0

Views: 1933

Answers (1)

Adam Dudley
Adam Dudley

Reputation: 126

I think you are missing a little bit in your changedata function, something like

function changedata(){
    testChart.data.datasets[0].data = ['4', '3', '2', '1', '2', '3', '4'];
    testChart.update();
}

Upvotes: 1

Related Questions