alanmanderson
alanmanderson

Reputation: 8200

Google Charts Pie Chart Event

I have the following code to generate several pie charts on my page:

for(var question in questions){
    console.log(question);
    var curChart = $('<div class="summary-chart"></div>');
    curChart.appendTo(contentDiv);
    var data = [["answer_text", "quantity"]];
    for(var answer in questions[question]){
        data.push([answer, questions[question][answer]]);
    }
    var data = google.visualization.arrayToDataTable(data);
    chart = new google.visualization.PieChart(curChart[0]);
    google.visualization.events.addListener(chart, 'select', function(){
        alert(this.getSelection().focusNode.data); //alert slice text
    });
    chart.draw(data, {title: question, pieHole: 0.3, pieSlieceText: 'percentage', backgroundColor: '#efefef'});
}

As you can see, when I click on a slice it will print the text of that slice. What I need is to set an ID on the table and fetch that ID inside of the event (where I have alert(this.getSelection().focusNode.data)).

I could certainly include the id in the outer div like:

var curChart = $('<div class="summary-chart" data-id="'+question+'"'></div>');

Now I just need to figure out how to get to that data in the alert.

Upvotes: 1

Views: 422

Answers (1)

WhiteHat
WhiteHat

Reputation: 61212

to prevent the value for question from becoming locked to the last value inside the event listener,
assign the event within a closure (function)

for(var question in questions) {
    if (questions.hasOwnProperty(question)) {
        drawQuestion(question);
    }
}

function drawQuestion(question) {
    var curChart = $('<div class="summary-chart"></div>');
    curChart.appendTo(contentDiv);
    var data = [["answer_text", "quantity"]];
    for(var answer in questions[question]){
        data.push([answer, questions[question][answer]]);
    }
    var data = google.visualization.arrayToDataTable(data);
    chart = new google.visualization.PieChart(curChart[0]);
    google.visualization.events.addListener(chart, 'select', function(){
        console.log(question, this.getSelection().focusNode.data);
    });
    chart.draw(data, {title: question, pieHole: 0.3, pieSlieceText: 'percentage', backgroundColor: '#efefef'});
}

Upvotes: 1

Related Questions