"Enhance Your Dataset in chart.js 2.0 with an Exciting New Property

Need assistance in adding a property to dataset/label for identification on click. Previous attempts include:

Chart.controllers.customBar = Chart.controllers.bar.extend({
        code: null
    });

Progress has been made as the new property "code" is visible, data is associated with it, however the chart background displays but no data from datasets are visible.

Here's my initialization:

var ctx = document.getElementById("roads-chart").getContext("2d");
    window.roadsBar = new Chart(ctx, {
        type: 'bar',
        data: roadsChartData,
        options: {
            title: {
                display: true,
                text: "Road Status"
            },
            tooltips: {
                mode: 'label'
            },
            responsive: true,
            scales: {
                xAxes: [{
                        stacked: true,
                    }],
                yAxes: [{
                        stacked: true
                    }]
            },
            onClick: function(e, d) {
                console.log(d);
            }
        }
    });

Seeking help with understanding Chart.js and demonstrations on extending functionalities. Can anyone assist?

Thank you

Answer №1

Instead of extending the chart, you can utilize internal properties like _datasetIndex and _index to access extra properties from the chart configuration:

  options: {
    onClick: function(e, d) {
      if (d.length > 0) {
        console.log(this.config.data.datasets[d[0]._datasetIndex].code[d[0]._index]);
      }
    }
    ...

Additionally, within the datasets section, define the extra property 'code' as shown below:

  ...
  datasets: [{
    code: ['a', 'b', 'c', 'd', 'e', 'f', 'g'],
    ...

To see this implementation in action, check out the Fiddle - http://jsfiddle.net/55cdvb20/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on changing query using Ajax and Laravel when clicking a link

I am currently facing a challenging issue that seems unsolvable (I'm struggling to even understand where to begin). I have a total of four hyperlinks: https://i.sstatic.net/kn5vx.png When landing on the page initially, all the links are displayed b ...

Retrieving the attribute for a chosen value from an asp:RadioButtonList using jQuery

I am currently maintaining an old C# codebase and encountering an asp:RadioButtonList... <asp:RadioButtonList AutoPostBack="false" TextAlign="Right" RepeatDirection="Horizontal" RepeatLayout="Flow" runat="server" ID="radIncidentType" /> ...that is ...

Troubleshooting: jQuery unable to locate element within iframe

I need help finding all elements within an iframe that contain a specific word, for example, 'stack' on this page: http://en.wikipedia.org/wiki/Stack_Overflow Here is the code I am currently using: <body> <iframe src="http://en.wik ...

Achieving a full-height div using CSS and HTML to fill the remaining space

Here is the current layout structure I am working with: div { border: 1px solid } <div id="col_1" style="float:left;width:150px;">1</div> <div id="col_2" style="float:left;width:100px;">2</div> <div id="col_3" style="float:l ...

Utilizing Zoomdata data in conjunction with echarts index.js to create a dynamic stacked line chart

I am currently working on integrating Zoomdata with an echarts javascript chart to visualize data from 20 different computers in a stacked line chart format. While I can manually code this setup, I am looking for a way to dynamically link the data from Zoo ...

What could be causing the recurring appearance of the success alert message in an AJAX call to a PHP script in this particular situation?

Below you will find two code blocks, each designed to handle an AJAX call to a PHP file upon clicking on a specific hyperlink: <script language="javascript" type="text/javascript"> $(".fixed").click(function(e) { var action_url1 = $(th ...

Utilizing Sequelize with Typescript for referential integrity constraints

After defining these two Sequelize models: export class Users extends Model<Users> { @HasMany(() => UserRoles) @Column({ primaryKey: true, allowNull: false, unique: true }) UserId: string; @Column({ allowNull: false, unique: tru ...

Dynamically parsing JSON data with jQuery

I have some JSON data that looks like this: { "default": [ [ 1325876000000, 0 ], [ 1325876000000, 0 ], [ 1325876000000, 0 ], [ 1325876000000, 0 ] ], "direct": [ [ ...

Modify the React state of a JSON object that stores an array as a value

Is there a way to add or remove an item from this list? const [addIconMenuList, setAddIconMenuList] = useState({ "body": ["Logo", "Chest Pocket", "Tag"], "hood": ["Logo"], "sleeves": ["Cuffs"] }) setAddIconMenuList((prevState) => ...

Swap out the string variable when it is modified

To generate a string inside the "code" variable that combines the selected image values, the final code should appear similar to: "test1/A=1a/B=1b" or "test2/A=1b/B=1a", etc. If the user modifies icon "A," it should replace the value in the code instead of ...

React-Redux Project: Issue with React components not displaying properly, only the Parent directory gets rendered

Luckily, I managed to resolve the webpack build issues successfully. Nevertheless, every time I execute 'npm start' (webpack-dev-server), it serves the parent directory of this file. The reason behind this behavior remains unclear. -I've cr ...

Exploring the application of conditional logic within HTML coding

I am working on ensuring that Part II of the HTML page only runs once all required information has been successfully submitted through the form. This particular issue is within a Flask application. I need to run Part II after Part I in order to prevent an ...

Display Bootstrap Modal using Typescript in Angular

Looking for some creative ideas here... My Angular site allows users to register for events by filling out a form. They can also register themselves and other people at the same time. https://i.sstatic.net/a44I7.png The current issue ~ when a user clicks ...

I encountered some problems with conflicting Angular dependencies, so I decided to delete the node_modules folder

An error has occurred: The module 'H:\All_Files\Scripts\Angular\example\node_modules\source-map\source-map.js' could not be found. Please ensure that the package.json file contains a correct "main" entry. ...

Equality and inequality in arrays

Could someone help clarify why these comparisons between different JavaScript arrays result in true? ["hello"] !== ["world"] [42] !== [42] ["apple"] != ["orange"] [7] != [7] ...

Is there a way for users to share their thoughts in response to the posts of

I'm looking to implement a feature that allows users to add comments on posts with an "add comment" button similar to what you see in platforms like Facebook. When the button is clicked, a small input box should open up and display the comment below t ...

What is the method for entering text into alerts with Protractor?

Attempting to access a webpage with a login alert requesting credentials. My search for how to switch to the alert box online has proven fruitless. How do I enter the username and password? In my previous attempt to automate this page using Selenium WebDr ...

What could be causing my server to not fully read my json file?

I created a function that sends a get request for fav.json and assigned the id="fav_button" button to execute this function. Additionally, I configured an express server. However, upon clicking the button, only the last item in the json file is displayed. ...

Unable to retrieve data from file input using jQuery due to undefined property "get(0).files"

I am facing an issue with retrieving file data in jQuery AJAX call from a file input on an ASP.NET view page when clicking a button. HTML <table> <td style="text-align:left"> <input type="file" id="AttachmenteUploadFile" name="Attachme ...

Functional programming: Retrieve the initial truthy output from executing an array of diverse functions using a particular parameter

As I delve into the world of functional programming in TypeScript, I find myself contemplating the most idiomatic way to achieve a specific task using libraries like ramda, remeda, or lodash-fp. My goal is to apply a series of functions to a particular dat ...