Chartjs to load data from html table - Javascript Chart.js

Javascript examples for Chart.js:Chart Data

Description

Chartjs to load data from html table

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.js"></script> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script> 
      <style id="compiled-css" type="text/css">

.chart-toggles a.enabled {
   color: red;
}


      </style> 
      <script type="text/javascript">
    $(window).load(function(){/*from  w  w w  . j  a  v  a2s. c o m*/
var lineChartData2 = {
    labels: generateLabelsFromTable(),
    datasets: generateDataSetsFromTable()
};
var ctx = document.getElementById("LineChart").getContext("2d");
lineChart = new Chart(ctx).Line(lineChartData2);
function generateLabelsFromTable() {
    var labels = [];
    var rows = jQuery("tr");
    rows.each(function (index) {
        if (index != 0)
        {
            var cols = $(this).find("td");
            labels.push(cols.first().text());
        }
    });
    return labels;
}
function generateDataSetsFromTable() {
    var data;
    var datasets = [];
    var rows = jQuery("tr");
    var data = [];
    rows.each(function (index) {
        if (index != 0)
        {
            var cols = $(this).find("td");
            cols.each(function (innerIndex) {
                if (innerIndex != 0)
                   data.push($(this).text());
            });
        }
    });
    var dataset = {
        fillColor: "rgba(238,155,0,0.2)",
        strokeColor: "rgba(217,0,0,1)",
        pointColor: "rgba(166,0,0,1)",
        pointStrokeColor: "#fff",
        pointHighlightFill: "#fff",
        pointHighlightStroke: "rgba(151,187,205,1)",
        data: data
    }
    datasets.push(dataset);
    return datasets;
}
    });

      </script> 
   </head> 
   <body> 
      <canvas id="LineChart"></canvas> 
      <table> 
         <tbody>
            <tr> 
               <th>head1</th> 
               <th>head2</th> 
            </tr> 
            <tr> 
               <td>date1</td> 
               <td>1</td> 
            </tr> 
            <tr> 
               <td>date2</td> 
               <td>2</td> 
            </tr> 
            <tr> 
               <td>date3</td> 
               <td>3</td> 
            </tr> 
         </tbody>
      </table>  
   </body>
</html>

Related Tutorials