jQuery DataTables - Custom Column Visiblity - javascript

I like to use jQuery DataTable Plugin and want to create something like this-
And when anyone click on "Column visibility" button, they will see like this-
But I don't like to have Global search Button and Pagination on top (because I have already a pagination in the bottom).
I only want that button.
So, what I have done is -
$(document).ready(function()
{
var dataTable = $('#employee-grid').DataTable(
{
processing: true,
serverSide: true,
//ajax: "employee-grid-data.php", // json datasource for AJAX Data
"ajax":
{
"url": "employee-grid-data.php",
//"type": 'POST',
"data": function ( d ) //Sending Custom Data for manupulating with elements out of the table
{
d.myKey = "myValue";
// d.custom = $('#myInput').val();
// etc
},
},
//"pagingType": "full_numbers", //Adding Last and First in Pagination
stateSave: true,
"language":{ //Custom Message Setting
"lengthMenu": "Display _MENU_ records per page", //Customizing menu Text
"zeroRecords": "Nothing found - sorry", //Customizing zero record text - filtered
"info": "Showing page _PAGE_ of _PAGES_", //Customizing showing record no
"infoEmpty": "No records available", //Customizing zero record message - base
"infoFiltered": "(filtered from _MAX_ total records)" //Customizing filtered message
},
"lengthMenu": [[5, 10, 25, 50, -1], [5, 10, 25, 50, "All"]], //For customizing number of data sets per page
dom: 'l<"toolbar">frtip Bfrtip', //"Bfrtip" is for column visiblity
initComplete: function() //Adding Custom button in Tools
{
$("div.toolbar").html('<button type="button" onclick="addNewEntry()">Add a New Record</button>');
},
buttons: [ //Column Visiblity Buttons
{
extend: 'colvis',
collectionLayout: 'fixed three-column',
postfixButtons: [ 'colvisRestore' ]
}
],
});
});
More Preciously-
dom: 'l<"toolbar">frtip Bfrtip',
buttons: [ //Column Visiblity Buttons
{
extend: 'colvis',
collectionLayout: 'fixed three-column',
postfixButtons: [ 'colvisRestore' ]
}
],
But I am finding something like this-
So, I want only Green Round and not Red Round.
What have I done wrong?

SOLUTION
Option dom can be a little confusing at first, but simply put, each letter in it is a DataTables feature. Also order of the letters describe their positioning on the page.
B - Buttons,
f - filtering input
r - processing display element
t - table
i - informational panel
p - pagination control
There are other letters and HTML markup supported. See dom option and Buttons - dom parameter
pages for more information.
Use the code below:
var dataTable = $('#employee-grid').DataTable({
// ... skipped ...
dom: 'Brtip',
buttons: [
{
extend: 'colvis',
collectionLayout: 'fixed three-column',
postfixButtons: [ 'colvisRestore' ]
}
]
});
DEMO
See this jsFiddle for code and demonstration.

You need to add dom option of dataTable while initializing as below:
$('#example').DataTable( {
"dom": '<"top"i>rt<"bottom"flp><"clear">'
});
You can see Source/Demo here
More Precise explanation

Related

How to controll two datatable using one lengthMenu

I have two tables in the same View/Page. I am using jquery datatable and to target both the table, I have used .display in both tables.
Question: Both the table has separate tableLength dropdown, How to target both using the top dropdown?
In Layman term, since both table has separate dropdown, both works properly for respective table. I want to use first table's dropdown and If I select 25, it should select 25 for the bottom dropdown and both the tables should show 25 records.
What I tried: I have made customized dropdown (orange box) which will call onChange event and will get the value and pass that value to Datatables "aLengthMenu" and "iDisplayLength" keys.
Below screenshot is taken from the UI I am working, can't paste the full picture. "Show 5 entries" is the LengthMenu.
`
<html>
.
.
<table class="display" id="tbl_result1">
</table>
<table class="display" id="tbl_result">
</table>
.
.
</html>
$('table.display').DataTable({
"aaSorting": [],
'aoColumnDefs': [{
'bSortable': false,
'aTargets': ['col-action']
}],
"zeroRecords": "No",
"language": {
"zeroRecords": " ",
"infoEmpty": " ",
"searchPlaceholder": "Search for an issue"
},
"aLengthMenu": [[5, 10, 25, -1], [5, 10, 25, "All"]], //LeftArray:value,rightArray: UI Dropdown
"iDisplayLength": 5, // By default rows
"searching": false,
"bStateSave": true,
"bPaginate": true, // true/false to enable/disable Pagination
"bInfo": false, // true/false to enable/disable the "Showing 1 of N records" message
"ordering": false, // true/false to enable/disable table sorting
'columnDefs': [{ // For disabling sorting in a particular table columns
'targets': [0], // column index (start from 0)
'orderable': false, // set orderable false for selected columns
}],
"fnStateSave": function (oSettings, oData) {
localStorage.setItem('offersDataTables', JSON.stringify(oData));
},
"fnStateLoad": function (oSettings) {
return JSON.parse(localStorage.getItem('offersDataTables'));
},
"dom": '<"pull-left"f><"pull-right"l>tip'
});
`
Tried calling onChange event listner and passing the value from customized dropdown, called a function that passes the value as an argument (let say variable is newLengthVal)to the Datatables like
`
"aLengthMenu": [[newLengthVal], [newLengthVal]], //LeftArray:value,rightArray: UI Dropdown
"iDisplayLength": newLengthVal, // By default rows
`

datatable, update footer info totalSize value without redrawing table

I have a datatable that gets called in a function like this:
function createDatatable(){
//get table data
var resp = getTableData()
var dataset = resp.data //table data
var total = resp.total //number like 238
//if table already exists
if (myProductGapsTable) {
myProductGapsTable.clear();
myProductGapsTable.rows.add(dataset); //add new dataset
//myProductGapsTable.language.reload(); //trying to get something like this to work
myProductGapsTable.draw();
} else {
//create table
myProductGapsTable = $('#myProductGapsTable').DataTable({
scrollY: "60vh",
scrollX: true,
scrollCollapse: true,
paging: false,
fixedColumns: true,
"autoWidth": true,
data: dataset,
retrieve: false,
"language": {
"emptyTable": "No table data availiable.",
"info": `Showing _START_ to _END_ of ${total} entries`,
},
"sDom": 'ti',
"paging": false,
"preDrawCallback": function (settings) {
pageScrollPos = $("#myProductGapsTableContainer div.dataTables_scrollBody").scrollTop();
},
"drawCallback": function (settings) {
$("#myProductGapsTableContainer div.dataTables_scrollBody").scrollTop(pageScrollPos);
},
buttons: [
{
extend: 'excelHtml5',
text: 'excel',
exportOptions: { rows: { selected: true, search: 'applied' } }
},
{
extend: 'csvHtml5',
text: 'csv',
exportOptions: { rows: { selected: true, search: 'applied' } }
},
],
select: {
style: 'multi',
selector: 'td:first-child',
search: 'applied'
},
order: [1, 'asc'],
});
}
}
I am trying to have the info field use a custom total number for the info footer, this works fine when the table is first created; it will load the number (238 initially) in the footer correctly. But when I call the function again, if the total number is changed (like now lets say total is 77), the footer info text will not show the updated 'out of 77' text that I would like it to have.
I have an if statement that checks if the table has already been created when the function is called, is there any way I can refresh or reload the table's language field? So I can refresh the table's lower dom info text when the if statement is called?
I don't know of a way to do this using the DataTables API, unfortunately, but here is a jQuery/DOM way:
function changeCountTotal() {
total = resp.total;
var info = $('#myProductGapsTable_info').html();
// Format is assumed to be: "Showing 1 to 10 of 1,234 entries"
var regex = /(Showing.*of ).+?( entries)/;
var updatedinfo = info.replace(regex, "$1" + total + "$2");
$('#example_info').html(updatedinfo);
}
This would need to be called after the redraw peformed by myProductGapsTable.draw();, to ensure the other parameters (_START_, _END_) are correctly re-evaluted by DataTables.
If you want to format the total for thousands separators (or whatever is appropriate for your locale), that would be something like this:
total = resp.total.toLocaleString()
(If there is a way to do this using the DataTables API, that would be a better answer, of course.)

How to show just the N first number of rows on DataTables? How to download all data after this?

I am trying to show only the first N rows of data on DataTables, but can't find a way.
Additionally, when I click the Copy or Excel buttons I want to download all the data, and not just the rows who are being show.
In my last try, I used paging and pageLength without success. Below is the code. My data is on tbldata:
var dtable = $("#dvTableAC").DataTable({
data: tbldata,
columns: [
{ title: "A" },
{ title: "B" },
{ title: "C" },
{ title: "D" }
],
"paging": false,
"pageLength": 50,
dom: 'Blfrtip',
buttons: [
'excel', 'copy'
]
});
Please not that you need an extra plugin to be able to use the buttons (excel, copy).
https://datatables.net/extensions/buttons/built-in
var dtable = $("#dvTableAC").DataTable({
data: tbldata,
columns: [
{ title: "A" },
{ title: "B" },
{ title: "C" },
{ title: "D" }
],
"paging": true,
"pageLenght":10,
dom: 'Blfrtip',
buttons: [
'excel', 'copy'
]
});
Datatables will show all the data you send to it, if you set paging to false, then pageLenght is not used. If you want to limit the total records that datatables show, you must send just those records to it. You can restrict the number on the mysql query using limit 10. But I don't know any method of not having pagination and show only a x amount of rows from the total.

Disabling ordering in jQuery DataTables stills loads with order icon

I have a 4 columns DataTable that needs ordering, except for first column. I tried using "columns": [ {"orderable": false}, null, null, null ], but the first column shows the ordering icon (caret) on page load.
When I order another column, the icon disappear from first column, but there is still the space where it was, breaking the column width. Is there any way to REALLY disable the ordering, in a way that it also doesn't add any special padding?
SOLVED:
#ShaktiPhartiyal answer fixed the sorting problems. The width problem was fixed by setting the autowidth option to false and using a little CSS.
CSS part
table.dataTable thead tr th:first-child,
table.dataTable tbody tr td:first-child {
width: 0px;
}
DataTables options
$(table).DataTable({
"paging": false,
"columnDefs" : [
{ targets: 0, sortable: false},
],
"order": [[ 3, "asc" ]],
"autoWidth": false
});
Even if you disable sorting for a column, the dataTables sort order still remain. By default order is [0, 'asc']; simply set order to target the #2 column instead :
var table = $('#example').DataTable({
//....
order: [[ 1, "asc" ]] //column indexes is zero based
});
Working Fiddle
To disable ordering / sorting in datatables you can use the following parameter:
"aoColumns": [{ "bSortable": false }, null],
The code tells datatable to disable sorting in the first column.

Hide LengthMenu from Jquery datatable

Please how do I hide the LengthMenu (the dropdownlist that displays number of records being shown per page) from my Jquery datatable?
Currently I am able to disable it, but I do not want it to appear at all. See my Fiddle here
below:-
testdata = [{"id":"58","country_code":"UK"},{"id":"59","country_code":"US"}];
$('#test').dataTable({
"aaData": testdata,
"aoColumns": [
{ "mDataProp": "id" },
{ "mDataProp": "country_code" }
],
"bLengthMenu" : false, //thought this line could hide the LengthMenu
"bInfo":false,
});
`//the next 2 lines disables the LengthMenu
//var aLengthMenu = $('select[name=test_length]');
//$(aLengthMenu).prop('display', 'disabled');
Try with
$('#test').dataTable({
"aaData": testdata,
"aoColumns": [
{ "mDataProp": "id" },
{ "mDataProp": "country_code" },
{ "mDataProp": "title" },
{ "mDataProp": "pubdate" },
{ "mDataProp": "url" }
],
"bLengthChange" : false, //thought this line could hide the LengthMenu
"bInfo":false,
});
Fiddle
Do it with:
"bLengthChange": false
This will hide the length dropdown.
As of DataTables 1.10.18, according to https://datatables.net/reference/option/lengthChange
This is the recommended method to hide lengthMenu:
$('#example').dataTable( { "lengthChange": false } );
Cheerrs
You can do it by disabling the pagination:
"bPaginate": false
To disable pagination at all, then do:
"paging": false
If using bootstrap or some other templates, the result of hiding the length menu could get a little ugly, like, missing borders.
What worked for me was to use css and manipulate the label tag
.dataTables_length label { display:none;}
If you want to hide the pagination and "Show X Entries" drop down option ONLY when the data rows can fit in a single page, you can use drawCallback:
"drawCallback": function (settings) {
var api = this.api();
var totalRows = api.rows().data().length; //Get total rows of data
var rowPerPage = api.rows({ page: 'current' }).data().length; //Get total rows of data per page
if (totalRows > rowPerPage) {
//Show pagination and "Show X Entries" drop down option
$('div.dataTables_paginate')[0].style.display = "block";
$('div.dataTables_length')[0].style.display = "block";
} else {
//Hide it
$('div.dataTables_paginate')[0].style.display = "none";
$('div.dataTables_length')[0].style.display = "none";
}
}
Alternatively, you can refer to this discussion, quite similar approach.

Categories

Resources