MaazKhan47
MaazKhan47

Reputation: 849

Add Series in Highcharts on the basis of user input

How to add series in highchart dynamically, the number of series depends up on the check boxes checked by the user

[Array[265], Array[259], Array[265], Array[256]]

Lets suppose I have an array-Parent of arrays-Child like above. The number of arrays-Child depends upon the checkboxes checked. Each arrays-Child should represent a series.

Upvotes: 0

Views: 612

Answers (1)

Rilke Petrosky
Rilke Petrosky

Reputation: 1185

List item

  • Add a checkbox for each child-array with an index data property
  • Set an onchange event to a function that pushes an item into the series property of the $.highchart for each checked checkbox.

$(function() {
  /* Build random Data */
  var randomData = [
    [], /* Child 0 */
    [], /* Child 1 */
    [], /* Child 2 */
    [], /* Child 3 */
  ].map(function(child) {
    for (var i = 1; i <= 31; i++) {
      child.push([Date.UTC(2016, 7, i), Math.random()]);
    }
    return child;
  });

  /* Append checkboxes to DOM */
  randomData.forEach(function(child, i) {
    $('#the-form').append('<input checked type="checkbox" data-index="' + i + '"> Series #' + (i + 1) + '<br>');
  });

  /* Chart drawing function */
  var redraw = function() {
    $('#the-chart').highcharts({
      chart: {
        zoomType: 'x'
      },
      title: {
        text: 'Random series data over time'
      },
      subtitle: {
        text: document.ontouchstart === undefined ?
          'Click and drag in the plot area to zoom in' : 'Pinch the chart to zoom in'
      },
      xAxis: {
        type: 'datetime'
      },
      yAxis: {
        title: {
          text: 'Some rate'
        }
      },
      legend: {
        enabled: false
      },
      plotOptions: {
        area: {
          marker: {
            radius: 2
          },
          lineWidth: 1,
          states: {
            hover: {
              lineWidth: 1
            }
          },
          threshold: null
        }
      },
      series: randomData.filter(function(child, i) {
        /* Choose checked only */
        return document.querySelector('input[data-index="' + i + '"]').checked
      }).map(function(child, i) {
        /* Then return as series */
        return {
          type: 'area',
          name: 'Series #' + (i + 1),
          data: child
        };
      })
    });
  };

  /* Call redraw on change */
  $('input[data-index]').on('change', redraw);

  /* And select the first one start */
  $('input[data-index]:first').val(true);
  redraw();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<h3>Select Series</h3>
<div id="the-form">
</div>
<div id="the-chart" style="min-width: 310px; height: 400px; margin: 0 auto"></div>

Upvotes: 2

Related Questions