Use If Statement to change default length of table

Use If Statement to change default length of table

KuronumaKuronuma Posts: 9Questions: 4Answers: 0
edited January 22 in Free community support

Hello!

I have an odd question that I'm hoping I can get some help with. My default table length is 10 rows, which is fine for most cases. However, it seems a little silly to show 10 rows if there only are, say, 11 rows in the table. Ideally, I'd like to make this setting conditional - if the number of rows is less than 15, set the length to 25. However, I can't seem to get it working. I'm using JQuery, and I'm a novice with it. Here's what I thought might work. This function is outside my initialization script.

var table = $('.TableStyle-SmartTable').DataTable();

table.each(function (value, index){
    if (table.rows.count() < 15) {
        table.page.len(25).draw();
        }
    });

My initialization script is pretty long because I've done a lot of customization, so I'd prefer not to create two separate scripts to support this use case. There are also cases where I have multiple tables on a page, so whatever solution I come up with would need to accommodate that.

Thank you in advance! I might ask some silly questions, so please be patient with me. :)

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,571Questions: 26Answers: 4,996
    edited January 22 Answer ✓

    table.rows.count()

    You are missing the () for the rows() API, Likely you will see an error in the browser's console for this statement.

    You will want to use either initComplete or ready() to execute the check to make sure Datatables has all the rows, especially if you are using ajax.

    You can define initComplete using config defaults which will apply to all Datatables on the page. However if you have initComplete defined in the individual Datatables configs they will take precedence.

    You can use tables() along with ready() to apply the check against all the Datatables. Here is an example using ready() for multiple Datatables:
    https://live.datatables.net/socirone/34/edit

    You will need to adjust the if statement to meet your requirements.

    Kevin

  • kthorngrenkthorngren Posts: 21,571Questions: 26Answers: 4,996

    If you choose the ready() solution then please monitor this thread for a change in using the API instance in the function.

    Kevin

  • KuronumaKuronuma Posts: 9Questions: 4Answers: 0
    edited January 23

    Thank you @kthorngren! Your answer was very helpful. I really appreciate you taking the time to help me with this! :) Here was my solution, I added it to my configuration options, as you suggested.

    initComplete: function (settings, json){
        var thisTable = $(this).DataTable();
        if (thisTable.rows().count() > 10 && thisTable.rows().count() < 15) {
            thisTable.page.len(25).draw();
        }
    }
    
Sign In or Register to comment.