Hide LengthMenu from Jquery datatable - javascript

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.

Related

How to pass values of a column of rows whose checkboxes are selected in jQuery Data Table

I have a datatable which is getting populated by an ajax call. Following is the code:
oTable = $('#lenderList').dataTable(
{
bServerSide: true,
bProcessing: true,
searching: true,
sAjaxSource: "loanAdminAjax?ajax=true&searchCol="+$('#category').val(),
sServerMethod: 'POST',
sPaginationType: "full_numbers",
columnDefs:[
{
targets:8,
checkboxes:{
selectrow:true
}
}
],
aoColumns: [
{
"sName": "loanApplicationNumber",
mData: "loanApplicationNumber"
},
{
"sName": "name",
mData: "name"
},
{
"sName": "submissionDate",
mData: "submissionDate"
},
{
"sName": "kycEmailId",
mData: "kycEmailId"
},
{
"sName": "appVersion",
mData: "appVersion"
},
{
"sName": "documentStatus",
mData: "documentStatus"
},
{
"sName": "latestRemark",
mData: "latestRemark"
},
{
"sName": "appName",
mData: "appName"
},
{
nData: "salaryTransaction",
render: function ( salaryTransaction, type, row ) {
if ( type === 'display' ) {
return '<input type="checkbox" class="editor-active">';
}
return salaryTransaction;
},
className: "dt-body-center"
}
],
dom: '<"button">lfrtip'
}
);
});
I have to consider all the loan application numbers of the respective rows whose checkboxes are checked by the user. So I can trigger an event on Click of a button but how can I get the values of Loan Application Number of those rows whose checkboxes are clicked.
I am new to javaScript. Please let me know how this can be achieved.
I have this idea : Loop through all the rows of the table, and test if the checkbox of that row is checked or not. If it is, then extract the value of the needed cell!
Try this :
$(document).ready(function(){
$("button").click(function(){
oTable = $("#lenderList").dataTable(); // Get the datatable,
var loanApplicationNumbers = []; // An array that will contain the "loan application numbers"
oTable.$('tr').each(function(index,rowhtml){ //Loop through the table rows
//Check the state of the checkbox
var checked= $('input[type="checkbox"]:checked',rowhtml).length;
if (checked==1){
//If the checkbox is checked, then add the inner text of the cell to the array
loanApplicationNumbers.push(rowhtml.children[1].innerText);
}
});
console.log(loanApplicationNumbers); //Do whatever you want
});
});
Note : rowhtml.children is an Array of cells in that row, if you want to get the value of the first cell, you should do rowhtml.children[0].innerText .

jQuery DataTables - Custom Column Visiblity

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

Grouping and Column Filtering on jQuery DataTable at different div

I am using jQuery DataTables with Grouping and Filtering on data. But both can't work together. Only one can work.
oTable = $('#schedule').dataTable({
'bLengthChange': false,
'bPaginate': false,
'bJQueryUI': true,
'processing': true,
"aoColumnDefs": [
{ "bSortable": false, "aTargets": ["no-sort"] }
]
}).columnFilter({
sPlaceHolder:"head:before"
}).rowGrouping({
sGroupingColumnSortDirection: "desc",
bExpandableGrouping: true,
bExpandSingleGroup: false,
iExpandGroupOffset: -1,
asExpandedGroups: ['Pending Action', 'In Operation']
});
Please give me advice on how to work with both and I want to add the filter field in different div.
It doesnt work because you are using chaining. You are accidently trying to initialise rowGrouping on whatever columnFilter() returns :
dataTable().columnFilter().rowGrouping()
< dataTable < columnFilter
Use another approach to initialise the plugins, for example in the initComplete callback (fnInitComplete if you are using 1.9.x) :
var table = $('#example').dataTable({
initComplete : function() {
this.columnFilter();
this.rowGrouping({
bExpandableGrouping: true,
asExpandedGroups: ["Other Browsers", "Trident"],
fnOnGrouped: function() { alert('Rows are regrouped!'); }
});
}
})
demo -> http://jsfiddle.net/y2s2b0an/

Sorting on a column in removing html contents in Datatables 1.10

I am unsing datatable 1.10, In my code in one of the column as per the requirement I am adding an HTML checkbox tag.
Now first time when the table gets rendered it shows me those checkboxes but when I click on that column to sort or any other column for sorting then the column which contains HTML contains are getting wiped out. (I crosschecked this with the chrome DOM inspector... the td element contains nothing :()
Below is my dataTable initialization code.
dataTableOptions: function() {
return {
"orderable": true,
"columnDefs": undefined,
"autoWidth": true,
"deferRender": true,
"data": undefined
};
},
dtRowGroupingOptions: function () {
return {
bExpandableGrouping: true,
bExpandSingleGroup: false,
iExpandGroupOffset: -1,
asExpandedGroups: [""]
};
}
var dataTablesOptions = self.dataTableOptions();
dataTablesOptions.data = tableData;
dataTablesOptions["paginate"] = false;
dataTablesOptions["lengthChange"] = false;
dataTablesOptions["columnDefs"] = [{"targets": 0, "data": "serverName", 'title' : 'ServerName'},
{"targets": 1, "data": "COMMAND", 'title' : 'Command'},
{"targets": 2, "data": "PID", 'title' : 'Process Id'},
{"targets": 3, "data": "SIZE", 'title' : 'Size'},
{"targets": 4, "data": "USER", 'title' : 'User'},
{"targets": 5, "data": "action", 'title' : 'Actions', "type" : "html", "orderDataType": "dom-checkbox"}
];
dataTablesOptions["createdRow"] = function (nRow, aData, iDataIndex) {
var self = this;
if (aData["comments"] && aData["comments"].indexOf("Error") != -1) {
// Do not do anything
$('td:eq(0)', nRow).html(aData["serverName"]+"" +
"<a class='btn btn-danger' href='#' data-toggle='tooltip' title='Error in execution'><i class='icon-question'></i></a>");
}
return self;
};
var dcInfoDataTable = contentDiv.find('table.dcInfoTable').DataTable(dataTablesOptions);
I am also using datatables rowGrouping and searchhiglight plugin, below is the code.
// call row grouping
contentDiv.find('table.dcInfoTable').dataTable().rowGrouping(self.dtRowGroupingOptions());
// enable search highlighing
contentDiv.find('table.dcInfoTable').dataTable().fnSearchHighlighting();
Note: I tried removing rowGrouping plugin code just to make sure that this is not happeing because of this plugin but even after removing there is no effect, the HTML contents are getting wiped out.
Not only when you sort will it clear out your data, it will also clear it if you use any other feature that changes your table. This happens because each time the datatable draws for new data, it's clearing out your static data.
You need to re-append the checkboxes on each draw, you can do this in the fnDrawCallback event:
$(document).ready( function() {
$('#example').dataTable( {
"fnDrawCallback": function( oSettings ) {
alert( 'DataTables has redrawn the table' );
//append the checkbox to your table columns here...
}
} );
} );

jQuery Datatables Columnfilter - external filter is not working on hidden column

I have a table with 2 columns. 1 column is hidden and I want to apply an external select-filter for it. The filter and the table are working fine - but the filter applys only for the visible column.
How can I apply the filter directly for the hidden column?
$('#example').dataTable({
"aoColumns": [
/* Region JUST FOR EXTERNAL FILTER*/ { "bVisible":false},
/* Babys */ null
],
});
$('#example').dataTable().columnFilter({
sPlaceHolder: "head:before",
aoColumns:[
{ sSelector: "#regionFilter", type: "select" },
]}
);
You have to add
"bUseColVis": true,
into your code!
It should look like:
$('#example').dataTable({
"aoColumns": [
/* Region JUST FOR EXTERNAL FILTER*/ { "bVisible":false},
/* Babys */ null
],
});
$('#example').dataTable().columnFilter({
sPlaceHolder: "head:before",
//ADD IT HERE
"bUseColVis": true,
aoColumns:[
{ sSelector: "#regionFilter", type: "select" },
]}
);

Categories

Resources