How to add the elements dynamically from the html table for chart.js

老子叫甜甜 提交于 2019-12-22 18:08:07

问题


Can anyone help with this issue?

I am using chart.js for developing charts into my asp.net mvc C# application.

The issue is I am unable to add the elements dynamically from the html table to the chart.

<canvas id="myChart" width="600" height="400"></canvas> //html5 canvas    
   <script type="text/javascript">    
            var ctx = document.getElementById("myChart").getContext("2d");    
            var data = {                                 
                datasets: [    
                           {
                              fillColor: "rgba(223,104,27,0.5)",    
                              strokeColor: "rgba(220,220,220,1)",    
                              data: getcountdata1()    
                            },    
                            {    
                               fillColor: "rgba(151,187,205,0.5)",    
                               strokeColor: "rgba(151,187,205,1)",    
                               data: getcountdata2()    
                          }]    
   myNewChart = new Chart(ctx).Line(data, options);

The above is working fine, becausse in datasets I am hardcoding the number of elements in datasets, but in reality this should check the HTML table and get the data from the table.

Now the question is how can I make the datasets to get dynamic values based on the number of rows in the table?

For example I have written a Javascript function (I have tried the following coed):

var data: 
{            
 datasets: getdata()
}

function getdata()
{
rows = document.getElementById('tblresult').getElementsByTagName('tbody')[0].getElementsByTagName('tr').length;    
for(i=0;i<rows;i++)
{
  datasetdata[i] = [
             {
                 fillColor: getrandomfillcolor(),    
                 strokeColor: getrandomstrokecolor(),    
                 data: getcountdata()

             }]
}

function getrandomfillcolor()
{
}

function getrandomstrokecolor()
{
}

function getcountdata()
{
}

return datasetdata

             }

I have tried several times but was not able to find a solution for this.


回答1:


You need to pass each row to getcountdata() function

rowsDomElements = document.getElementById('tblresult').getElementsByTagName('tbody')[0].getElementsByTagName('tr');

for(i=0;i<rowsDomElements.length;i++)
{
    datasetdata[i] = [
    {
         fillColor: getrandomfillcolor(),
         strokeColor: getrandomstrokecolor(),
         data: getcountdata(rowsDomElements[i])
    }]
}

function getcountdata(row)
{
    //create data as needed
}


来源:https://stackoverflow.com/questions/17869827/how-to-add-the-elements-dynamically-from-the-html-table-for-chart-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!