Search code examples
javascripthighchartsdatatables

Datatables and Highcharts - table.on('draw' and function chartData(table)


I managed to buid a Highcharts more or less the way I wanted based on a table that is similar to what I can get through Datatables, see working example. Unfortunately, when I link the Highcharts to my Datatables, the Highcharts is blank, probably beccause I am missing the

table.on('draw', function () {
});

and the

function chartData(table) {
}

parts of my js, as described here or here.

Would you know how I could write these parts to fit my case? I don't need to count, sum or average the data, but just read the value in the Datatables.


Solution

  • You can build Highcharts series structure based on datatables. For example:

    const table = new DataTable('#example1');
    const chart = Highcharts.chart("container", {
      chart: {
        type: "line"
      },
      title: {
        text: "Test Data"
      },
      xAxis: {
        type: 'category'
      },
      series: chartSeries(table)
    });
    
    table.on('draw', function() {
      chart.update({
        series: chartSeries(table)
      }, true, true);
    });
    
    function chartSeries(table) {
      const series = [];
      // Count the number of entries for each office
      table
        .rows({
          search: 'applied'
        })
        .data()
        .each(function(rowData, a, b) {
          const xData = rowData[0];
    
          rowData.forEach((data, index) => {
            if (index) {
              if (!series[index - 1]) {
                series[index - 1] = {
                  name: $(table.column(index).header()).html(),
                  data: []
                };
              }
    
              series[index - 1].data.push({
                name: xData,
                y: parseFloat(data.replace(/,/g, ''))
              });
            }
          });
        });
    
      return series;
    }
    

    Live demo: https://jsfiddle.net/BlackLabel/jtxw8b5d/

    API Reference: https://api.highcharts.com/class-reference/Highcharts.Chart#update