Reputation: 106
I am trying to pass the graph type dynamically by selecting the options from the select list. Below is my code :
<html>
<head>
</head>
<body>
<select id="ChartType" name="ChartType" onchange="drawChart()">
<option value = "0">Select Chart Type
<option value="PieChart">PieChart
<option value="Histogram">Histogram
<option value="LineChart">LineChart
<option value="BarChart">BarChart
</select>
<div id="chart_div" style="border: solid 2px #000000;" ></div>
<p id="demo"></p>
<p id="demo1"></p>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
['Mushrooms', 3],
['Onions', 4],
['Olives', 1],
['Zucchini', 5],
['Pepperoni', 2]
]);
var a = document.getElementById("ChartType").value;
document.getElementById("demo1").innerHTML = "You selected: " + a;
// Set chart options
var options = {
'title':'How Much Pizza I Ate Last Night',
'width':400,
'height':300
};
// Instantiate and draw our chart, passing in some options.
//passing the value which I am reading after selecting the options from the select.
var chart = new google.visualization.document.getElementById("ChartType").value(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</body>
</html>
However I am unable to get the graph. I am trying to select the option as Histogram and I want the graph to be Histogram and if I am selecting Pie-Chart the graph should be Pie-Chart with the same value.
Upvotes: 1
Views: 70
Reputation: 1096
You have an error on this line:
var chart = new google.visualization.document.getElementById("ChartType").value(document.getElementById('chart_div'));
it should be:
var chart = new google.visualization[document.getElementById("ChartType").value](document.getElementById('chart_div'));
To use a string as a key, you have to use []
. Here's why:
var a = "someProperty";
var myObject = {
someProperty: 3,
a: 4
};
console.log(myObject.a); // 4
console.log(myObject[a]); // 3
console.log(myObject.someProperty); // 3
console.log(myObject["someProperty"]); // 3
Upvotes: 1