Skip to content
Advertisement

Click on interactive chart.js bar chart and get value for labels and groups in JS

I’m building an webapp where you choose airline companies and get a bar chart with scores in five categories(company, food, luggage, punctuality, staff). I want to get a value for company name and category, when a user clicks different parts of the chart. It’s to do further things in Python using the values for company name and category.

For example, in the image below, when a user clicks the big green bar(fourth bar from the right), I want my JS to receive company="Air France", category="punctuality". I assume I need to do something with onclick but cannot figure out…

enter image description here

Context: Based on the companies you choose in the form box, a Python backend returns a json data to JS. In JS addGroupBarChart draws a chart using Chart.js and embeds it in the canvas element in html.

This is an excerpt from JavaScript

JavaScript

data and labels arguments that go into addGroupBarChart looks like

JavaScript

I tried several solutions including this one, but it made my app not show the chart even after clicking “Show chart” button. I started learning JS last week so quite noob… Any help would be appreciated. Thank you!

Advertisement

Answer

You can define an onClick event handler, which unfortunately is poorly documented. In your case, it would look as follows, onBarClicked being your own function that is invoked with company and category.

JavaScript

Please have a look at your amended code below:

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement