Chartjs-ChartJS dataset onclick deselect the rest

0👍

You need to write a custom function under legend’s onClick property in chart options which can look like below code:

legend: {
      onClick: function(e, legendItem) {
        var index = legendItem.datasetIndex;
        var ci = this.chart;
        var alreadyHidden = (ci.getDatasetMeta(index).hidden === null) ? false : ci.getDatasetMeta(index).hidden;
        var anyOthersAlreadyHidden = false;
        var allOthersHidden = true;

        ci.data.datasets.forEach(function(e, i) {
          var meta = ci.getDatasetMeta(i);

          if (i !== index) {
            if (meta.hidden) {
              anyOthersAlreadyHidden = true;
            } else {
              allOthersHidden = false;
            }
          }
        });

        if (alreadyHidden) {
          ci.getDatasetMeta(index).hidden = null;
        } else {
          ci.data.datasets.forEach(function(e, i) {
            var meta = ci.getDatasetMeta(i);

            if (i !== index) {
              if (anyOthersAlreadyHidden && !allOthersHidden) {
                meta.hidden = true;
              } else {
                meta.hidden = meta.hidden === null ? !meta.hidden : null;
              }
            } else {
              meta.hidden = null;
            }
          });
        }

        ci.update();
      },
    } 

If you wish to see the working fiddle -> http://jsfiddle.net/km0bpq9s/

Hope it helps!

Leave a comment