Search code examples
amcharts

Dynamic checkbox toggle to stack / unstack AMCharts 4 XY columnseries / bar chart


I have a checkbox placed separately of my XY columnseries chart. The original chart has each series.stacked = true. This works fine. I have a listener on the checkbox to toggle from the stacked columns to independent columns. It sets (toggles) the same stacked property on each series. Unfortunately nothing updates. I have tried calling invalidateData() on the chart after the property assignment - but that also doesn't work to update the stacking / unstacking function.

    $("#chartAssetsTimelineIndividualColumns").change(function () {

        chartAssetsTimeline.series.values.forEach(function (series) {

            series.stacked = !this.checked;
        });
    });

Solution

  • this doesn't refer to the input element when you're inside the forEach method as it is scoped to the window object at that point. You'll want to save a reference to it and use that instead, or just use the event object that the change method provides. Also, you should use the each function instead of iterating over the read-only values array.

    $('#chartAssetsTimelineIndividualColumns').change(function() {
      var that = this;
      chartAssetsTimelineIndividualColumns.series.each(function(series) {
        series.stacked = !that.checked;
      });
    });
    
    // or
    $('#chartAssetsTimelineIndividualColumns').change(function(e) {
      chartAssetsTimelineIndividualColumns.series.each(function(series) {
        series.stacked = !e.target.checked;
      });
    });    
    
    // or, preferably, with VanillaJS:
    document.getElementById('chartAssetsTimelineIndividualColumns').addEventListener('change', function(e) {
      chartAssetsTimelineIndividualColumns.series.each(function(series) {
        series.stacked = !e.target.checked;
      });
    });