0

I am creating a data dashboard and I have stumbled on a problem that has me completely stumped. I am using chart.js as the chart renderer and jquery/js for the control of the dashboard. I want a user to be able to add a new chart via a button click, I can render the html content easily using the following:

   $('.graphs').append('<canvas id="' + name + '" data-dataset="2323"></canvas>');

This is creates the html as required, however chart.js requires a chunk of javascript per graph for the options and the dataset. I have no idea how to create this element of the application, I cant find any documentation that supports this method of dynamic graph creation. I am reasonably proficient at jquery, but this has me scratching my head.

I am looking for a method on how to create this code dynamically:

 new Chart(document.getElementById(name), {
                type: 'bar',
                data: {
                    labels: ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"],
                    datasets: [{
                        label: "Sales (millions)",
                        backgroundColor: ["#3e95cd"],
                        data: datasets1
                    }]
                },
                options: {
                    legend: {
                        display: false
                    },
                    title: {
                        display: false,
                        text: 'Example Bar Chart'
                    },
                    scales: {
                        xAxes: [{
                            gridLines: {
                                display: false
                            }
                        }],
                        yAxes: [{
                            gridLines: {
                                display: true
                            }
                        }]
                    }
                },

            });

Or some other approach.

1
  • You can do one thing. Just send an Ajax call on click of new chart button and then return html from that file and append that in a div. That will hopefully print the graph. Please try that and then let me know. Commented Jul 15, 2021 at 11:19

1 Answer 1

1

Modifying the solution in this post is the only way I have found to achieve what I wanted. I cant take the credit as the answer here helped a lot: Create multiple chart.js charts from jsonfile data

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.