I have a data.json file that contain 4 objects : a , b , c , d.
I declared my variables manually.
var chart_a = new google.visualization.PieChart(document.getElementById('sa-piechart-a'));
var chart_b = new google.visualization.PieChart(document.getElementById('sa-piechart-b'));
var chart_c = new google.visualization.PieChart(document.getElementById('sa-piechart-c'));
var chart_d = new google.visualization.PieChart(document.getElementById('sa-piechart-d'));
Now, I want to make it dynamically so it can handle all the objects in my JSON file, and it doesn't break - when I add more objects to my JSON file.
So while in the loop, I tried add :
chart[object] = new google.visualization.PieChart($('#sa-piechart-'+ object.toLowerCase() )); // <---- I try to add this line
I got my objects from Ajax call.
var data = {};
var chart = {};
for (var object in objects) {
var total = objects[object].danger + objects[object].warning + objects[object].success ;
data[object] = google.visualization.arrayToDataTable([
['Piechart' , 'Number of Skills'],
['danger' , ( objects[object].danger/total ) * 100 ],
['warning' , ( objects[object].warning/total ) * 100 ],
['success' , ( objects[object].success/total ) * 100 ],
]);
//console.log( '#sa-piechart-' + object.toLowerCase() ); // Return #sa-piechart-a
chart[object] = new google.visualization.PieChart($('#sa-piechart-'+ object.toLowerCase() )); // <---- I try to add this line
}
// var chart_a = new google.visualization.PieChart(document.getElementById('sa-piechart-a'));
// var chart_b = new google.visualization.PieChart(document.getElementById('sa-piechart-b'));
// var chart_c = new google.visualization.PieChart(document.getElementById('sa-piechart-c'));
// var chart_d = new google.visualization.PieChart(document.getElementById('sa-piechart-d'));
I keep getting Uncaught Error: Container is not defined
Any hints / suggestions will be much appreciated !
Container is not defined
means that DOM element is not found as mentioned in the comments. You would need to dynamically create the elements and then pass them to google pie chart. Something like this should do.
var el = document.getElementById('sa-piechart-' + object);
if (!el) {
el = document.createElement('div');
el.id = object;
document.body.appendChild(el); // <--- I added to body. Add to required element
}
chart[object] = new google.visualization.PieChart(el);
chart[object].draw(data[object]);
Here is a demo http://jsfiddle.net/6M2sH/443/
A much fancier solution (using jQuery)
var $el = $('#sa-piechart-' + object).length ? $('#sa-piechart-' + object) : $('<div id="#sa-piechart-' + object+'"></div>').appendTo('body');
chart[object] = new google.visualization.PieChart($el[0]);
Fancier demo http://jsfiddle.net/6M2sH/444/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.