最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Chart js old chart data not clearing - Stack Overflow

programmeradmin2浏览0评论

This question has been asked many times and I went through most of them but non of them helped me finding a solution.

I am generating couple of bar charts using a for loop as a part of reporting functionality.

I am using node.js with Express Handlebars.

My page looks like:

<div class="row report-charts">
    <div class="col-md-12">
    {{#buildings}}
        <div class="col-md-6">
           <h4>{{Name}}</h4>
           <canvas id="{{idBuildings}}" width="200" height="80"></canvas>
        </div>
    {{/buildings}}
    </div>
</div>

My js code looks like:

$('.case-report-btn').click(function(){

        $.ajax({
            type: 'post',
            url: '/reports/cases/filter',
            data : {
                StartDate : $('.start-ms-time-hidden').val(),
                EndDate : $('.end-ms-time-hidden').val(),
                ReportKey : $('.cases-filter-type').val()
            },
            dataType: 'json',
            success: function(res) {
                $('.report-charts').show();
                for(key in res) {
                    var innerObj = res[key]; //gives the inner obj
                    var ctx = document.getElementById(key); //the idBuildings
                    var labels = [];
                    var data = [];
                    var buildingName = innerObj.Name;
                    for(innerKey in innerObj) {
                        if(innerKey != 'Name' && innerKey != 'Total') {
                            labels.push(innerKey);
                            data.push(innerObj[innerKey]);
                        }
                    }

                    var options = {
                        type: 'bar',
                        data: {
                            labels: labels,
                            datasets: [{
                                label: buildingName,
                                data: data,
                                backgroundColor: 'rgba(255, 99, 132, 0.2)',
                                borderColor: 'rgba(255,99,132,1)',
                                borderWidth: 1
                            }]
                        },
                        options: {
                            scales: {
                                yAxes: [{
                                    ticks: {
                                        beginAtZero:true,
                                        fixedStepSize: 1
                                    }
                                }]
                            }
                        }
                    }
                    var myChart = new Chart(ctx, options);
                }
                $('#pleaseWaitDialog').modal('hide');
            },
            error: function(err) {
                $('#pleaseWaitDialog').modal('hide');
                bootbox.alert('Error: ' + err);
            }
        });
    });

So basically, I am using for loop to generate multiple charts on the page. Inside the loop I declared the chart variable, every time I change the report parameters and hit the button, the new chart is generated. But when I hover over it, the old one still shows up.

Now I am not sure where I should be putting the myChart.destroy() or myChart.clear() methods. I also tried moving the myChart declaration outside the for loop but it didn't help either.

Any suggestions on how to handle this?

This question has been asked many times and I went through most of them but non of them helped me finding a solution.

I am generating couple of bar charts using a for loop as a part of reporting functionality.

I am using node.js with Express Handlebars.

My page looks like:

<div class="row report-charts">
    <div class="col-md-12">
    {{#buildings}}
        <div class="col-md-6">
           <h4>{{Name}}</h4>
           <canvas id="{{idBuildings}}" width="200" height="80"></canvas>
        </div>
    {{/buildings}}
    </div>
</div>

My js code looks like:

$('.case-report-btn').click(function(){

        $.ajax({
            type: 'post',
            url: '/reports/cases/filter',
            data : {
                StartDate : $('.start-ms-time-hidden').val(),
                EndDate : $('.end-ms-time-hidden').val(),
                ReportKey : $('.cases-filter-type').val()
            },
            dataType: 'json',
            success: function(res) {
                $('.report-charts').show();
                for(key in res) {
                    var innerObj = res[key]; //gives the inner obj
                    var ctx = document.getElementById(key); //the idBuildings
                    var labels = [];
                    var data = [];
                    var buildingName = innerObj.Name;
                    for(innerKey in innerObj) {
                        if(innerKey != 'Name' && innerKey != 'Total') {
                            labels.push(innerKey);
                            data.push(innerObj[innerKey]);
                        }
                    }

                    var options = {
                        type: 'bar',
                        data: {
                            labels: labels,
                            datasets: [{
                                label: buildingName,
                                data: data,
                                backgroundColor: 'rgba(255, 99, 132, 0.2)',
                                borderColor: 'rgba(255,99,132,1)',
                                borderWidth: 1
                            }]
                        },
                        options: {
                            scales: {
                                yAxes: [{
                                    ticks: {
                                        beginAtZero:true,
                                        fixedStepSize: 1
                                    }
                                }]
                            }
                        }
                    }
                    var myChart = new Chart(ctx, options);
                }
                $('#pleaseWaitDialog').modal('hide');
            },
            error: function(err) {
                $('#pleaseWaitDialog').modal('hide');
                bootbox.alert('Error: ' + err);
            }
        });
    });

So basically, I am using for loop to generate multiple charts on the page. Inside the loop I declared the chart variable, every time I change the report parameters and hit the button, the new chart is generated. But when I hover over it, the old one still shows up.

Now I am not sure where I should be putting the myChart.destroy() or myChart.clear() methods. I also tried moving the myChart declaration outside the for loop but it didn't help either.

Any suggestions on how to handle this?

Share Improve this question edited Jul 27, 2017 at 8:21 Wasif Ali 8941 gold badge13 silver badges30 bronze badges asked Jul 27, 2017 at 6:03 codeinprogresscodeinprogress 3,5018 gold badges52 silver badges76 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

I think there are a few ways to do it. You can update your chart data if the chart already exist. Here two functions you can use:

function removeData(chart) {
    chart.data.labels.pop();
    chart.data.datasets.forEach((dataset) => {
        dataset.data.pop();
    });
    chart.update();
}

function addData(chart, label, data) {
    chart.data.labels.push(label);
    chart.data.datasets.forEach((dataset) => {
        dataset.data.push(data);
    });
    chart.update();
}

First you have to remove all your data and then add the new data.

If you want to destroy the chart and create it again you have to save your variable as global. To do this you have yo declare your variable like window.myChart and then before create the new chart, something like this:

if (window.myChart) window.myChart.destroy();
window.myChart = new Chart(ctx, options);

Another way you can try is removing your canvas and creating another one. Something like this:

$('#your_canvas').remove();
$('#your_canvas_father').append('<canvas id="your_canvas"></canvas>');
发布评论

评论列表(0)

  1. 暂无评论