Miguel Flores
Miguel Flores

Reputation: 147

Clear/Reinitialize Highchart

I'm using Highcharts.js plugin at the moment everything it's ok but while I was testing my char I discovered that if a call my draw chart function twice I get the results that I expect two times, so now I want to clear chart content or reinitialize or destroy or whatever before call it again but I don't know exactly what to do, searching here for a solution I found this:

myChar.destroy();

But in this case myChar is a variable where they put all the chart options and my problem is that I do this in a function, so what can I do to create a reset function for example, here is my code and what I tried:

$(document).ready(function() {
  $('#bt').click(function() {
    chart();
  });
  $('#bt2').click(function() {
    $('#MyDiv').html("");
  });
});

function chart() {

  $('#Chart').highcharts({
    chart: {
      type: 'bar'
    },
    title: {
      text: 'Inspeccion Dimensional'
    },
    xAxis: {
      categories: ['Pieza 1', 'Pieza 2', 'Pieza 3', 'Pieza 4', 'Pieza 5']
    },
    yAxis: {
      min: 0,
      title: {
        text: 'Resultados'
      }
    },
    legend: {
      reversed: true
    },
    plotOptions: {
      series: {
        stacking: 'normal'
      }
    },


    series: [{
      name: 'Thickness',
      data: [2, 2, 3, 2, 1]
    }, {
      name: 'Width',
      data: [2, 2, 3, 2, 1]
    }, {
      name: 'Length',
      data: [2, 2, 3, 2, 1]
    }, {
      name: 'Diameter',
      data: [3, 4, 4, 2, 5]
    }]
  });
}
<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>


<button id="bt">
  Draw
</button>

<button id="bt2">
  Clear
</button>

<div id="MyDiv">
  <div id="Chart">
  </div>
</div>

If you see my code I tried to solve this using $('#MyDiv').html("") but if I do this in this way I'm not able to draw my chart again. Fiddle with working code

Upvotes: 1

Views: 8501

Answers (2)

Asad Sarwar
Asad Sarwar

Reputation: 583

add the following code in the button 2 event:

$('#Chart').highcharts().destroy();

Upvotes: 1

Shekhar Pankaj
Shekhar Pankaj

Reputation: 9125

You need to destroy the instance of Highchart.

$('#bt2').click(function () {
    $('#Chart').highcharts().destroy();
 });

Updated Fiddle

Upvotes: 2

Related Questions