Hitesh
Hitesh

Reputation: 3498

Pass dynamic variables in options to Google Charts

I am trying to pass a Series number in a Google Chart option through a variable. However it is not accepting it as a variable and instead is taking it as a string. You can see in Image1 that I have passed in Series parameter SecondseriesColumnNumber as a variable and value is 1.

Image 1 Image 1

However in the output it is considering it as a string but not as the series number as shown below

Image 2

enter image description here

Other parameters are considering the values correctly but not the series one. How can I make this work? My code is below

var options = {
    title: title,
    width: width,
    height: height,
    bar: { groupWidth: '75%' },
    chartArea: { left: "8%", right: "8%", top: "10%", width: "100%", height: "75%" },
    backgroundColor: 'transparent',
    tooltip: { textStyle: { color: 'black' }, isHtml: true },
    isStacked: isStacked,
    seriesType: seriesType,
    series: { SecondseriesColumnNumber: { type: SecondseriesType } },
    hAxis: { slantedText: true }
};

var chart = new google.visualization.ComboChart($('DivSeries')[0]);

Upvotes: 0

Views: 1225

Answers (1)

WhiteHat
WhiteHat

Reputation: 61212

the problem has to do with JavaScript syntax.
you are not able to use a variable as a key in the definition of an object.
you must first create the object, then you can add additional keys using variables.

there are two ways to get / set values of object keys, once the object is defined.
both of the following will return the same value for title.

var title = options.title;
var title = options['title'];

where as in the latter, we can substitute a variable for the title key.

var key = 'title';
var title = options[key];

in this case, define the static options as needed.

var options = {
    title: title,
    width: width,
    height: height,
    bar: { groupWidth: '75%' },
    chartArea: { left: "8%", right: "8%", top: "10%", width: "100%", height: "75%" },
    backgroundColor: 'transparent',
    tooltip: { textStyle: { color: 'black' }, isHtml: true },
    isStacked: isStacked,
    seriesType: seriesType,
    series: {},
    hAxis: { slantedText: true }
};

then you can use a variable to further define the series option.

var SecondseriesColumnNumber = 1;
options.series[SecondseriesColumnNumber] = { type: SecondseriesType };

Upvotes: 2

Related Questions