简体   繁体   中英

How would I fill a table from highchart data?

If I have a chart and a table like below and I want to pass the chart data into the table cells. How would I pass it?

 Highcharts.chart('container', { chart: { type: 'bar' }, series: { data: [100,200, 300], }, }); 
 <div id="container"></div> <table id="dataTable"> <thead> <tr> <th>First Column</th> <th>Second Column</th> <th>Third Column</th> </tr> </thead> <tbody> <tr> <td></td> <td></td> <td></td> </tr> </tbody> </table> 

Here is a basic way you can use Highcharts and jQuery to fill the cells of your HTML table with the data from your chart.

First, we want to set a placeholder row in your table where we'll fill in the data. I've given this row the ID of RowToFill so we can refer to it in the Javascript.

HTML:

<div id="container" style="height: 400px"></div>

<table id="dataTable">
    <thead>
        <tr>
            <th>First Column</th>
            <th>Second Column</th>
            <th>Third Column</th>
        </tr>
    </thead>
    <tbody>
        <tr id="RowToFill">
        </tr>
    </tbody>
</table>

Next, we'll go through the chart's data and add table cells to our placeholder row using the jQuery append() function.

Javascript:

/* set the chart to a variable so you can get to the data later */
var thisChart = Highcharts.chart('container', {
    chart: {
        type: 'bar'
    },
    xAxis: {
        categories: ['A', 'B', 'C']
    },
    series: [{
        data: [100,200,300]
    }]
});

/* go through each item in the chart series */
$(thisChart.series[0].data).each(function( index ) {
    /* add a table cell to the row where it should go */
    $('#RowToFill').append('<td>' + this.y + '</td>');
});

Here's a working fiddle with this solution: http://jsfiddle.net/brightmatrix/5ad8fgzp/

To make this more flexible, you could modify this function to first run through a list of x-axis categories to create the table header row. This would make the number of cells in your table body row match the number of data points in your chart.

I hope this is helpful for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM