New datases do not shows Chart js

Using line chart js. Need to make checkbox which show/hide datasets

I made something like this:

lineChartData = {
                        labels : ["01.01.2015","012.01.2015","03.01.2015","04.01.2015","05.01.2015","06.01.2015","07.01.2015"],
                        datasets : dataSets
                    };

where dataSets is array of dataset objects, and when checkbox changed i do the next:

                    if($(this).prop('checked')){

                                myNewChart.datasets[datasetId] = dataSets[datasetId];
                            }
                    else{
                                myNewChart.datasets[datasetId]= {};
                            }

                            myNewChart.update();

myNewChart.datasets[datasetId]= {}; Works and delete line on graph, but adding dataset back not showing the line, however it added in myNewChart.datasets array.

Upvotes: 0

Views: 425

Answers (1)

potatopeelings
potatopeelings

Reputation: 41075

Just destroy and redraw the chart. While Chart.js does support adding and removing line points - it is by label (and not by dataset - which is what you want)

Your problem was that you were emptying out the actual dataset objects - if you link it to a copy of the dataset everything works.

Here is your updated change handler

$('input:checkbox').change(function () {
    var chartId = $(this).attr('data-chart-id');
    var datasetId = $(this).attr('data-data-set');

    dataSets[datasetId].hide = !$(this).prop('checked')

    lineChartData.datasets = []
    dataSets.forEach(function (dataset) {
        // create a copy of the dataset to modify (if required) and put into the chart dataset array
        var copy = jQuery.extend(true, {}, dataset)
        if (dataset.hide)
            copy.data = []
        lineChartData.datasets.push(copy)
    })

    // create the graph from scratch
    myNewChart.destroy()
    myNewChart = new Chart(ctx).Line(lineChartData, chartOpt);
});

Fiddle - http://jsfiddle.net/6qdm7nwu/

Upvotes: 1

Related Questions