Daybreaker Daybreaker - 1 month ago 14
HTML Question

Create dynamic chart with chart.js

I am using Chart.js jquery plugin to create bar chart . I can create static chart but i want to create a dynamic chart. I want to draw the chart from the data which read from a html table. How to set dynamic dataset to a chart.js bar chart.

This is my code.

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Bar Chart</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<script src="js/Chart.js"></script>
</head>
<body>

<div style="width:50%;">
<canvas id="canvas_bar"></canvas>
</div>

<div class="dataset">
<table>
<tr>
<th>Year</th>
<th>Income</th>
<th>Expenditure</th>
<th>Profit/Loss<th>
</tr>
<tr>
<td>2012</td>
<td>10000</td>
<td>5000</td>
<td>5000</td>
</tr>
<tr>
<td>2013</td>
<td>11500</td>
<td>7500</td>
<td>4000</td>
</tr>
<tr>
<td>2014</td>
<td>9800</td>
<td>4700</td>
<td>5100</td>
</tr>
<table>
<div>



<script>
var randomScalingFactor = function(){ return Math.round(Math.random()*100)};

var barChartData = {
labels : ["2012","2013","2014"],
datasets : [
{
fillColor : "rgba(95,137,250,0.5)",
strokeColor : "rgba(95,137,250,0.9)",
highlightFill: "rgba(95,137,250,0.75)",
highlightStroke: "rgba(95,137,250,1)",
data : [10000,11500,9800]
},
{
fillColor : "rgba(245,75,75,0.5)",
strokeColor : "rgba(245,75,75,0.8)",
highlightFill : "rgba(245,75,75,0.75)",
highlightStroke : "rgba(245,75,75,1)",
data : [5000,7500,4700]
},
{
fillColor : "rgba(98,223,114,0.5)",
strokeColor : "rgba(98,223,114,0.8)",
highlightFill : "rgba(98,223,114,0.75)",
highlightStroke : "rgba(98,223,114,1)",
data : [5000,4000,5100]
}
]

};
window.onload = function(){
var ctx = document.getElementById("canvas_bar").getContext("2d");
window.myBar = new Chart(ctx).Bar(barChartData, {
responsive : true
});
}
</script>
</body>
</html>

Answer

you can extract values from table by using jquery text() function , by building correct data structure for chart.js you can generate chart data dynamically from table .

First of all you have to extract labels from table . you can select rows and by iterating each row you can get label data from first columns.

function generateLabelsFromTable()
{                       
    var labels = [];

    var rows = jQuery("tr");
    rows.each(function(index){
        if (index != 0)  // we dont need first row of table
        {
            var cols = $(this).find("td");      
            labels.push(cols.first().text());                           
        }
    });
    return labels;
}

Similarly you can generate chart data by iterating the table html .

function generateDataSetsFromTable()
{
    var data;
    var datasets = [];
    var rows = jQuery("tr");
    rows.each(function(index){
        if (index != 0) // we dont need first row of table
        {
            var cols = $(this).find("td");  
            var data = [];
            cols.each(function(innerIndex){
                if (innerIndex!=0) // we dont need first columns of the row                 
                    data.push($(this).text());                                          
            });


            var dataset = 
            {
                fillColor : colors[index%3].fillColor,
                strokeColor : colors[index%3].strokeColor,
                highlightFill: colors[index%3].highlightFill,
                highlightStroke: colors[index%3].highlightStroke,
                data : data
            }

            datasets.push(dataset);

        }
    });
    return datasets;
}

After writing this functions , you can modify your barChartData like this

var barChartData = {
    labels : generateLabelsFromTable(),
    datasets : generateDataSetsFromTable()
}; 

You also should define a color array into the begining to keep the current style of the chart . This array is used above when assigning chart dataset

var colors = [];
colors.push(                        
{
        fillColor : "rgba(95,137,250,0.5)",
        strokeColor : "rgba(95,137,250,0.9)",
        highlightFill: "rgba(95,137,250,0.75)",
        highlightStroke: "rgba(95,137,250,1)"
});
colors.push(                        
{
        fillColor : "rgba(245,75,75,0.5)",
        strokeColor : "rgba(245,75,75,0.8)",
        highlightFill : "rgba(245,75,75,0.75)",
        highlightStroke : "rgba(245,75,75,1)"
});
colors.push(                        
{
        fillColor : "rgba(98,223,114,0.5)",
        strokeColor : "rgba(98,223,114,0.8)",
        highlightFill : "rgba(98,223,114,0.75)",
        highlightStroke : "rgba(98,223,114,1)",
});

Do not forget to include jquery .

FIDDLE