Search code examples
javascriptcanvasjs

CanvasJS, issues with setting a user input Title for chart


I am currently facing an issue with creating a user input title for a canvasJS chart. I am currently running through the tutorial over at canvasJS, and I thought it would make a neat small project to create a user input oriented pie chart.

The current issue I am facing is trying to get the text inputted from HTML to show up correctly.

[JSFiddle]https://jsfiddle.net/n3n0pssc/

var chart = new CanvasJS.Chart("chartContainer",{
               title:{
document.getElementById("chartTitle").setAttribute("text")
}`

I understand that the title must be set by tying it together with the addDataPointsAndRender function, but I am confused as canvasJS only displays set text by title: {text : "title"} and I am trying to figure out how it would go together by fetching input text.

Thank you for any assistance.


Solution

  • You can set the user inputs to the chart by either using chart options or by using the set() methods of the CanvasJS API.

    I have modified your jsfiddle, and its working now.

    function addDataPointsAndRender(){
        chart.options.title.text =document.getElementById("chartTitle").value;
        chart.options.data[0].dataPoints.push({ 
            y: parseFloat(document.getElementById("yValue1").value),
            indexLabel: document.getElementById("indexLabel1").value
        });
        chart.render();
    }
    

    Also have a look at :

    1. Tutorial on Rendering chart from user Input
    2. Updating Chart Options
    3. CanvasJS Methods & Properties Documentation