Skip to content

Instantly share code, notes, and snippets.

@vctls
Created May 25, 2018 09:10
Show Gist options
  • Save vctls/1a7f99990c257dd0154695317b4684b2 to your computer and use it in GitHub Desktop.
Save vctls/1a7f99990c257dd0154695317b4684b2 to your computer and use it in GitHub Desktop.
Datatables | dynamically generated column show/hide buttons
var $t = $('#datatable');
var $dt = $t.DataTable();
/*===================*/
/* Show/hide buttons */
/*===================*/
var $toolbar = $("<div class='toolbar'></div>");
$dt.columns().every(function () {
var that = this;
console.log(that.header().innerHTML);
$toolbar.append(
"<button class='btn btn-sm btn-default "
+ (that.visible() ? 'active' : '')
+ "' name='column-toogle' data-toggle='button' data-column='"
+ that.index()
+ "'>" + that.header().innerHTML
+ "</button>"
)
});
$("#datatable-gestavs-contrat-select_wrapper").prepend($toolbar);
// Set button actions.
$('button[name="column-toogle"]').on('click', function () {
// Get column index.
var column = $dt.column($(this).attr('data-column'));
// Toggle visibility.
column.visible(!$(this).hasClass('active'));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment