How to put back the data with a switch?

I have chart (using chartjs), and a switch button. When I click on the switch, new data will be added to the chart (and erase the previous one). But what I’m trying to do, is when I click back on the switch, it’ll display the previous data.

Here is my code :

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"
        integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ=="
        crossorigin="anonymous"></script>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
    <script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>

</head>
<body>
    <div class="row mt-3">
        <div class="col-md-12">
            <div style="width:75%; margin: 0 auto;">
                <canvas id="myChart"></canvas>
            </div>
            <div class="form-check form-switch">
                <input class="form-check-input" type="checkbox" id="checkBox" onclick="updateChart()">
                <label class="form-check-label" for="checkBox">Catégories</label>
            </div>
        </div>
    </div>


     <script>
        var test1 = [0, 10, 5, 2, 20, 30, 45, 60, 43, 22, 11, 23];
        var test2 = [90, 80, 75, 62, 50, 40, 35, 11, 2, 24, 28, 34];

        var ctx = document.getElementById('myChart').getContext('2d');
            var chart = new Chart(ctx, {
                // The type of chart we want to create
                type: 'line',

                // The data for our dataset
                data: {
                    labels: ['January', 'February', 'test3', 'test4', 'test5', 'test6', 'test7', 'test9', 'test10', 'test11', 'test12'],
                    datasets: [{
                        label: 'My test1',
                        fill : false,
                        borderColor: 'rgb(255, 99, 132)',
                        data: test1,
                    }]
                },

                // Configuration options go here
                options: {}
            });

            function updateChart(){
                chart.data.datasets[0].label = 'My test2';
                chart.data.datasets[0].data = test2;
                chart.data.datasets[0].borderColor = '#F1FC00';
                chart.update();
            }
    </script>

</body>
</html>

Answer

Your updateChart function is only making the chart use the test2 data and it’s not smart to revert it when unchecked. You need to explicitly code it:

Change the onclick handler to onchange and change the function’s name:

<input class="form-check-input" type="checkbox" id="checkBox" onchange="toggleCategories(event)">
...
function toggleCategories(e){
  if (e.target.checked) {
    chart.data.datasets[0].label = 'My test2';
    chart.data.datasets[0].data = test2;
    chart.data.datasets[0].borderColor = '#F1FC00';
  } else {
    chart.data.datasets[0].label = 'My test1';
    chart.data.datasets[0].data = test1;
    chart.data.datasets[0].borderColor = 'rgb(255, 99, 132)';
  }
  chart.update();
}
...

The working code:

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"
        integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ=="
        crossorigin="anonymous"></script>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
    <script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>

</head>
<body>
    <div class="row mt-3">
        <div class="col-md-12">
            <div style="width:75%; margin: 0 auto;">
                <canvas id="myChart"></canvas>
            </div>
            <div class="form-check form-switch">
                <input class="form-check-input" type="checkbox" id="checkBox" onchange="toggleCategories(event)">
                <label class="form-check-label" for="checkBox">Catégories</label>
            </div>
        </div>
    </div>


     <script>
        var test1 = [0, 10, 5, 2, 20, 30, 45, 60, 43, 22, 11, 23];
        var test2 = [90, 80, 75, 62, 50, 40, 35, 11, 2, 24, 28, 34];

        var ctx = document.getElementById('myChart').getContext('2d');
            var chart = new Chart(ctx, {
                // The type of chart we want to create
                type: 'line',

                // The data for our dataset
                data: {
                    labels: ['January', 'February', 'test3', 'test4', 'test5', 'test6', 'test7', 'test9', 'test10', 'test11', 'test12'],
                    datasets: [{
                        label: 'My test1',
                        fill : false,
                        borderColor: 'rgb(255, 99, 132)',
                        data: test1,
                    }]
                },

                // Configuration options go here
                options: {}
            });

            function toggleCategories(e){
                if (e.target.checked) {
                  chart.data.datasets[0].label = 'My test2';
                  chart.data.datasets[0].data = test2;
                  chart.data.datasets[0].borderColor = '#F1FC00';
                } else {
                    chart.data.datasets[0].label = 'My test1';
                  chart.data.datasets[0].data = test1;
                  chart.data.datasets[0].borderColor = 'rgb(255, 99, 132)';
                }
                chart.update();
            }
    </script>

</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *