Chart.js to load new data on click - Javascript Chart.js

Javascript examples for Chart.js:Chart Data

Description

Chart.js to load new data on click

Demo Code

ResultView the demo in separate window

<html lang="en">
   <head> 
      <title>  Osman Raif G?ne?</title> 
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css"> 
   </head> 
   <body translate="no"> 
      <button class="btn-load" data-chart="data">set 1</button> 
      <button class="btn-load" data-chart="data2">set 2</button> 
      <canvas id="myChart" width="400" height="400"></canvas> 
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> 
      <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script> 
      <script>
      Chart.defaults.global.legend.display = false;
Chart.defaults.global.tooltips.enabled = false;
var options = {//from   ww w  .  j  ava  2 s .  c o m
   responsive: true,
   scale: {
      ticks: {
         beginAtZero: true
      },
      reverse: false
   }
};
var data = {
   labels: ["Brasil", "Argentina", "Chile", "M?xico", "Peru", "Paraguai", "Bol?via", "Haiti"],
   datasets: [{
       data: [31.60, 36.57, 23.49, 23.52, 20.34, 21.99, 35.31, 19.37],
       backgroundColor: ['rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)', 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)']
   }]
};
var data2 = {
   labels: ["Brasil", "Argentina", "Chile", "M?xico", "Peru", "Paraguai", "Bol?via", "Haiti"],
   datasets: [{
       data: [41.90, 43.95, 25.83, 27.59, 22.58, 24.45, 41.94, 21.96],
       backgroundColor: ['rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)', 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)']
   }]
};
var ctx = $("#myChart");
var myChart;
function createChart(teste){
  if(myChart)
  {
    myChart.destroy();
  }
   myChart = new Chart(ctx, {
      type: 'polarArea',
      data: teste,
      options: options,
   });
}
createChart(data);
$('.btn-load').on('click', function(){
  var foo = eval($(this).data('chart'));
   console.log(foo);
   createChart(foo);
});
      </script>  
   </body>
</html>

Related Tutorials