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

Can anyone help with this problem?

I am using chart.js to develop charts in my asp.net mvc c # application.

The problem is that I cannot dynamically add elements 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 works fine because in datasets I hardcode the number of elements in the datasets, but in fact this should check the HTML table and get the data from the table.

Now the question is, how can I get data sets to receive dynamic values โ€‹โ€‹based on the number of rows in the table?

For example, I wrote a Javascript function (I tried the following code):

 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 tried several times but could not find a solution for this.

+2
javascript html html-table charts
source share
1 answer

You need to pass each line to getcountdata()

 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 } 
0
source share

All Articles