user3376703 user3376703 - 5 months ago 32
Javascript Question

Getting lengthmenu value from datatable

I have the following option as part of:

"lengthMenu": [[10, 20, 50, 100, -1], [10, 20, 50, 100, "All"]],


and I'm attempting to get the value selected for lengthMenu. However, after looking through the jquery API I cannot seem to find anything to get this value after it has been changed. Any possible solutions you guys can think of?

Answer

The DataTables Documentation has what you are looking for! The page.info() function will return a lot of different information about the paging of a DataTable, including the number of records shown on each page (the selected value for lengthMenu).

Here's a list of all the objects that will be returned by the page.info() call (all the things you can reference like how the above example does:

{
    "page": 1, //current page (0 based index)
    "pages": 6, //total number of pages
    "start": 10, //index of first element on page
    "end": 20, //index of last element on page
    "length": 10, //lengthMenu setting - this is what you want -
    "recordsTotal": 57, //total number of records
    "recordsDisplay": 57, //total number of records to display after filtering
    "serverSide": false //whether or not serverside processing is used
}

With all this in mind, what you actually want will look like this

var table = $('#example').DataTable(); //note that you probably already have this call
var info = table.page.info();
var lengthMenuSetting = info.length; //The value you want

All of this (in more detail and with some examples) is availiable at the link provided above.

EDIT: Actually, if all you want is the page length, you can use table.page.len() to just get the length of the page, instead of getting table.page.info().length.

Comments