I've been looking for a way to click on/off google line charts from the legend. In my searches I came across this code on StackOverflow:
google.visualization.events.addListener(chart, 'select', function () {
var sel = chart.getSelection();
// if selection length is 0, we deselected an element
if (sel.length > 0) {
// if row is undefined, we clicked on the legend
if (sel[0].row === null) {
var col = sel[0].column;
if (columns[col] == col) {
// hide the data series
columns[col] = {
label: data.getColumnLabel(col),
type: data.getColumnType(col),
calc: function () {
return null;
}
};
// grey out the legend entry
series[col - 1].color = '#CCCCCC';
}
else {
// show the data series
columns[col] = col;
series[col - 1].color = null;
}
var view = new google.visualization.DataView(data);
view.setColumns(columns);
chart.draw(view, options);
}
}
});
(associated jsfiddle: http://jsfiddle.net/xDUPF/53/ )
However, I'm having trouble applying it to my chart, no matter where I put it in the scheme of things I either have no effect or no chart = \
Could anyone help me understand where in my code this needs to go? (I'm sorry, not a coder, just kinda stringing bits together to get something to work)
My code:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart1);
function drawChart1() {
var dataTable = new google.visualization.DataTable();
dataTable.addColumn('string', 'Month');
//loop from above for store and store base
<?php echo($cstores); ?>
dataTable.addRows([
<?php
$sql = "SELECT
QUOTE(DATE_FORMAT(date_submitted,'%b-%y')) AS 'Month'
". $string ."
FROM data
WHERE store_list IN (" . $user_stores . ")
GROUP BY YEAR(date_submitted), MONTH(date_submitted)
ORDER BY YEAR(date_submitted) ASC, MONTH(date_submitted) ASC";
$query = mysqli_query($conn,$sql);
foreach( $query as $key => $array ) {
echo("[");
foreach( $array as $attribute => $value ) {
echo str_replace("|","\
",$value) . ","; //couldn't put \
in the SQL above as it rendered in the output and broke it, so replacing the | here with \
so it renders properly in the chart
}
echo("],");
}
?>
]);
var options = {
title: '',
vAxis: {
minValue: 0,
maxValue: 10,
<?php if($submittedValue == 3){ // adjust chart scale and axis if MPO
echo("format: '#\'%\'',");
echo("title: 'Percent',");
}
else{
echo("title: 'Score 0-10'");
}
?>
},
legend: {
position: 'bottom',
},
pointSize: 10,
pointShape: 'diamond'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(dataTable, options);
}
The $cstores
just outputs a dynamic column header for the chart and then I fetch in some SQL depending on a form to match which makes my chart quite dynamic (all thanks to people here on StackOverflow) just struggling to get this last bit done!
Thank you