How can I dynamically build lengthMenu?

How can I dynamically build lengthMenu?

HillChris1234HillChris1234 Posts: 27Questions: 13Answers: 2
edited July 2016 in Free community support

I want to dynamically build what entries show up in the "show __ entries" drop down. I know I can use the lengthMenu option. It is a serverSide datatable, so I'm passing recordsTotal back from the .Net MVC Controller via Json. But, how can I use that to calculate the entries? Maybe I want to do something like this:

var intPageSize = [10];
intPageSize.push("recordsTotal" / 2);
intPageSize.push(-1);
...
"lengthMenu": intPageSize

...so that, if there are 50 records, it will include 10, 25, 50.

Likewise, if there are 80 records, it will contain 10, 40, 80.

How can I do this?

Answers

  • allanallan Posts: 61,669Questions: 1Answers: 10,096 Site admin

    There is no API presented by DataTables to change the options in the length menu after initialisation I'm afraid. Having said that, there is no reason why you couldn't just manipulate it directly using jQuery / DOM methods. DataTables doesn't redraw it (i.e. recreate the elements) after initialisation, so any options you add would be available for use.

    Allan

  • HillChris1234HillChris1234 Posts: 27Questions: 13Answers: 2
    edited July 2016

    When you say "manipulate it directly," do you mean something like this?

            "lengthMenu": function (d) {
                var intPageSize = [10];
                intPageSize.push(d.recordsTotal / 2);
                intPageSize.push(-1);
                return intPageSize;
            }
    

    ...because, that doesn't seem to do anything. It doesn't hit a breakpoint in the function (in Chrome DevTools), and the dropdown comes out empty.

  • allanallan Posts: 61,669Questions: 1Answers: 10,096 Site admin

    No I mean something like:

    $('div.dataTables_length select').append( '<option value="500">500</option>' );
    

    Allan

This discussion has been closed.