Dynamically show/hide columns in DataTables 1.10

2020-06-23 08:42发布

Im trying to implement dynamically hide/show on a checkbox (onChange event) using code the example section of the DataTables homepage.

function(e){
    //e.preventDefault();
    console.log($(this).attr('datacolumn'));

    // Get the column API object
    var column = table.column($(this).attr('datacolumn'));

    // Toggle the visibility
    column.visible( ! column.visible() );
}

However I get an error. It says table.column is "undefined"

Uncaught TypeError: undefined is not a function

I've tried changing the scope of the table-variable in order for me to interact with it in the console of Chrome. And as far as I can see it just points to a htmlcontent.

UPDATE

It worked when I specified the complete path to the object.

var column = $('#example').dataTable().api().column($(this).attr('datacolumn'))

标签: datatables
1条回答
等我变得足够好
2楼-- · 2020-06-23 09:24

in addition, here is a very simple script to dynamically add toggle buttons based on table thead content in a div on top of the table and bind a click to toggle visibility for each

$(document).ready(function() {
var table = $('#example').DataTable();
	
	// for each column in header add a togglevis button in the div
	$("#example thead th").each( function ( i ) {
		var name = table.column( i ).header();
		var spanelt = document.createElement( "button" );
		spanelt.innerHTML = name.innerHTML;						
		
		$(spanelt).addClass("colvistoggle");
		$(spanelt).attr("colidx",i);		// store the column idx on the button
		
		$(spanelt).on( 'click', function (e) {
			e.preventDefault(); 
			// Get the column API object
			var column = table.column( $(this).attr('colidx') );
			 // Toggle the visibility
			column.visible( ! column.visible() );
		});
		$("#colvis").append($(spanelt));
	});
} );
<div id="colvis"></div>
<table id="example" class="display" cellspacing="0" width="100%">
  <thead>
    <!-- here your col header -->
    </thead>
  <tbody>
  <!-- here your table data -->
  </tbody>
</table>

查看更多
登录 后发表回答