Chartjs-How to put back the data with a switch?

2👍

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/bootstrap@5.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/chart.js@2.8.0"></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>

0👍

You can not go back because in your updateChart method you always use test2 data and My test2 headline.

You need a way to keep track of your current state (Categories toggle on or off) and decide which headline and data to use when changing it.

There are multiple ways of doing this, here is one:

/*
  These are constants and represent the two different chart modes.
  You can come up with more descriptive names
*/
const CHART_MODE_1 = 'CHART_MODE_1'
const CHART_MODE_2 = 'CHART_MODE_2'

/* Initialise chartMode with correct first state */
var chartMode = CHART_MODE_1

function updateChart(){
   if (chartMode === CHART_MODE_1) {
     /* Update your chart with data2 here and switch to chartMode 2 */
   } else {
     /* Update your chart with data1 here and switch to chartMode 1 */
   }
}

Again, multiple ways to go about it. The important part is you need some way to keep track of what state are you currently in and decide what to do when you change it.

You can also keep track of your state with integer:


let toggleCounter = 0

function updateChart(){
   /* This time you can check if your counter is a prime number */
   if (i % 2 === 0) {
     /* Update your chart with data2 here and switch to chartMode 2 */
   } else {
     /* Update your chart with data1 here and switch to chartMode 1 */
   }
   /* Increment your toggleCounter (change your state) */
   toggleCounter++
}

The snippet below solves your problem:

<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/bootstrap@5.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/chart.js@2.8.0"></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];

        const CHART_MODE_1 = 'CHART_MODE_1'
        const CHART_MODE_2 = 'CHART_MODE_2'

        var chartMode = CHART_MODE_1

        var ctx = document.getElementById('myChart').getContext('2d');
        var chart = new Chart(ctx, {
            type: 'line',
            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,
              }]
            },
            options: {}
        });

        function updateChart(){
          if (chartMode === CHART_MODE_1) {
            chartMode = CHART_MODE_2
            chart.data.datasets[0].label = 'My test2';
            chart.data.datasets[0].data = test2;
            chart.data.datasets[0].borderColor = '#F1FC00';
          } else {
            chartMode = CHART_MODE_1

            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 comment