Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

datatables number of columns

How do i get the number of columns in a datatable?

I can get the number of rows by doing oTable.fnGetData().length but how do I get the number of columns so I can Iterate over each cell like this:

var numColumns = //How to get the number of columns?
    for(var r=0;r<oTable.fnGetData().length;r++){
        for(var c=0;c <= numColumns;c++){
            console.log("[R]: "+r+ "[C]: "+c+ " data: "+oTable.fnGetData(r,c));   
        }
    }
like image 919
Astronaut Avatar asked May 30 '12 00:05

Astronaut


People also ask

How many records can DataTables handle?

According to MSDN DataTable Class "The maximum number of rows that a DataTable can store is 16,777,216"

What are DataTable columns?

The columns option in the initialisation parameter allows you to define details about the way individual columns behave. For a full list of column options that can be set, please see the related parameters below.

How can you identify a column in a DataTable choose by using the row index by using the column default value by using the column index by using the column name?

This is Expert Verified Answer. By using the Column name or Column index we can identify a column in a data table.

How do I make my data table scrollable horizontally?

DataTables has the ability to show tables with horizontal scrolling, which is very useful for when you have a wide table, but want to constrain it to a limited horizontal display area. To enable x-scrolling simply set the scrollX parameter to be true .


2 Answers

GET NUMBER OF COLUMNS

  • DataTables 1.9+

    // Get number of all columns
    var numCols = $('#example').dataTable().fnSettings().aoColumns.length;
    
    // Get number of visible columns
    var numCols = $('#example thead th').length;
    

    See this jsFiddle for demonstration.

  • DataTables 1.10+

    // Get number of all columns
    var numCols = $('#example').DataTable().columns().nodes().length;
    
    // Get number of visible columns
    var numCols = $('#example').DataTable().columns(':visible').nodes().length;
    
    // Get number of visible columns (alternative way)
    var numCols = $('#example thead th').length;
    

    See this jsFiddle for demonstration.

ITERATE OVER EACH CELL

  • DataTables 1.10.6+

    $('#example').DataTable().cells().every( function (rowIndex, colIndex) {
        var data = this.data();
    
        console.log("Row:", rowIndex, "Col:", colIndex, "Data:", data);
    });
    
like image 77
Gyrocode.com Avatar answered Oct 17 '22 21:10

Gyrocode.com


The fnGetData can be used to get a single data row. So, you can simply check the length of the data row for the number of columns.

Example:

oTable.fnGetData(someRowNumber).length;

The above will return the number of columns in that data row.

like image 27
c0deNinja Avatar answered Oct 17 '22 21:10

c0deNinja