min.yong.yoon
min.yong.yoon

Reputation: 490

Cannot modify highcharts initilized as a global variable

I was playing around with highcharts. Now I know what I want, I was trying to make a simple logic that updates the data (xaxis categories) and its series dynamically. But I am stuck in the basics. I am not able to access the highchart from a simple function, although its a global var.

    <script>

        var myChart;
        $(document).ready(function() {
            init();
        });

        function init(){
            myChart = $('#graph-container').highcharts({
                title: {
                    text: 'Dummy Title'
                },
                xAxis: {
                    categories: ['Dummy1', 'Dummy2']
                },
                series: []
            });
        }

        function onclickButton(){
            //myChart.xAxis[0].setCategories(['A','B']);
            myChart.addSeries({
                    name: 'John',
                    data: [['A',1], ['B',2]]
                });
        }
    </script>
</head>
<body>
    <div id="graph-container" style="width:100%; height:400px;"></div>
    <input type="button" value="Click me" onclick="onclickButton()">
</body></html>

It says xAxis is not defined, or that addSeries function does not exist. What am I doing wrong?

Upvotes: 0

Views: 291

Answers (1)

hifebriansyah
hifebriansyah

Reputation: 341

checkout my snipet, hopefully it help you. have a nice day!

<html>

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://code.highcharts.com/highcharts.js"></script>
  <script>
    var myChart;

    $(document).ready(function() {
      init();
    });

    function init() {
      myChart = Highcharts.chart('graph-container', {
        title: {
          text: 'Dummy Title'
        },
        xAxis: {
          categories: ['Dummy1', 'Dummy2']
        },
        series: []
      });
    }

    function onclickButton() {
      myChart.addSeries({
        name: 'John',
        data: [
          ['A', Math.floor(Math.random() * 10)],
          ['B', Math.floor(Math.random() * 10)]
        ]
      });
    }
  </script>
</head>

<body>
  <div id="graph-container" style="width:100%; height:400px;"></div>
  <input type="button" value="Click me" onclick="onclickButton()">
</body>

</html>

Upvotes: 1

Related Questions