maurymmarques maurymmarques - 5 months ago 131
Javascript Question

How to add links to chart.js (Doughnut Charts)?

I would like to add links to doughnut charts to be able to send the user for a page with the records filtered by the clicked option.

For example here, if the user click on "Green", I want to send the user to a page that will show all "Green" records.

I didn't find a easy way to do that, and tried something like this that isn't working yet:

(I added a attribute "filter" with the "id" that I need to filter it)

var data = [
{
value: 300,
color:"#F7464A",
highlight: "#FF5A5E",
label: "Red",
filter: 1
},
{
value: 50,
color: "#46BFBD",
highlight: "#5AD3D1",
label: "Green",
filter: 2
},
{
value: 100,
color: "#FDB45C",
highlight: "#FFC870",
label: "Yellow",
filter: 3
}
]

$(document).ready(
function () {
$("#chart").click(
function(evt){
var activePoints = chart.getSegmentsAtEvent(evt);
var url = "http://example.com/?grid[f][collor][]=" + activePoints[0].filter
alert(url);
}
);
}
);


I'm not being able to get the attribute "filter" using "activePoints[0].filter"

Thank you.

Answer

Adding custom properties in JSON is a feature that may be on the roadmap for v2 (https://github.com/nnnick/Chart.js/issues/1185). As it currently stands, you can add properties in javascript doing something like this:

var segments = chart.segments;
for (var i = 0; i < segments.length; i++) {
  segments[i].filter = i+1;
}

Here's a jsfiddle with the filter/id property loading in the url (http://jsfiddle.net/tcy74pcc/1/):

If you want to do this with a chart based on points rather than segments, here's a post with a similar solution for lines: Displaying custom dataset properties in tooltip in chart.js

Hope that helps. Best of luck!

Comments