How to set 'pageLength' property programmatically?

How to set 'pageLength' property programmatically?

jQuery_NewbiejQuery_Newbie Posts: 3Questions: 2Answers: 0

In order to take into consideration the screen size, I would like to set programatically the 'pageLength' property of my DataTables rather than setting a hard-coded number.

Here is my current code:

$(document).ready(function () {
    // Initialize tabs
    $("#tabs").tabs();

    // Fetch data when the page loads and when the combo box value changes
    fetchData($('#comboBox').val());

    // When the combo box value changes, reload the data
    $('#comboBox').change(function () {
        fetchData($(this).val());
    });

    function fetchData(selectedValue) {
        // Show loading indicator (optional)
        $('#grid1 tbody').html('<tr><td colspan="5">Loading...</td></tr>');
        $('#grid2 tbody').html('<tr><td colspan="5">Loading...</td></tr>');

        // Use AJAX to fetch the data for both grids based on the selected value
        $.ajax({
            url: 'getData.php',
            method: 'GET',
            data: { selected_id: selectedValue },
            dataType: 'json',
            success: function (response) {
                if ($.fn.dataTable.isDataTable('#grid1')) {
                    $('#grid1').DataTable().destroy();
                }

                if ($.fn.dataTable.isDataTable('#grid2')) {
                    $('#grid2').DataTable().destroy();
                }

                // Fill grid 1
                let grid1Html = '';
                if (response.grid1 && response.grid1.length > 0) {
                    response.grid1.forEach(function (item) {
                        const itemNameLink = `<a href="${item['Link']}" target="_blank">${item.RoseName}</a>`;
                        grid1Html += `<tr><td>${itemNameLink}</td><td>${item.RoseType}</td><td>${item.RoseColor}</td><td>${item.RoseYear}</td><td>${item.RoseHybridizer}</td></tr>`;
                    });
                } else {
                    grid1Html = '<tr><td colspan="5">No data available</td></tr>';
                }
                $('#grid1 tbody').html(grid1Html);  // Update the grid1 tbody with the HTML

                // Fill grid 2
                let grid2Html = '';
                if (response.grid2 && response.grid2.length > 0) {
                    response.grid2.forEach(function (item) {
                        const itemNameLink = `<a href="${item['Link']}" target="_blank">${item.RoseName}</a>`;
                        grid2Html += `<tr><td>${itemNameLink}</td><td>${item.RoseType}</td><td>${item.RoseColor}</td><td>${item.RoseYear}</td><td>${item.RoseHybridizer}</td></tr>`;
                    });
                } else {
                    grid2Html = '<tr><td colspan="5">No data available</td></tr>';
                }
                $('#grid2 tbody').html(grid2Html);  // Update the grid2 tbody with the HTML

                // Initialize DataTable for grid1 if it has rows
                if ($('#grid1 tbody tr').length > 0) {
                    $('#grid1').DataTable({
                        paging: true,               // Enable pagination
                        searching: true,            // Enable searching
                        order: [],                  // Disable initial ordering
                        pageLength: 10,             // Set the number of rows per page (adjust as needed)
                        lengthChange: false,        // Disable the option to change the number of rows per page
                        info: true,                 // Optionally, disable the information text (e.g., "Showing 1 to 10 of 50 entries")
                        dom: 'lrtip'                // Remove the length drop-down (l), search box (f), and other elements as needed
                    });
                }

                // Initialize DataTable for grid2 if it has rows
                if ($('#grid2 tbody tr').length > 0) {
                    $('#grid2').DataTable({
                        paging: true,               // Enable pagination
                        searching: true,            // Enable searching
                        order: [],                  // Disable initial ordering
                        pageLength: 10,             // Set the number of rows per page (adjust as needed)
                        lengthChange: false,        // Disable the option to change the number of rows per page
                        info: true,                 // Optionally, disable the information text (e.g., "Showing 1 to 10 of 50 entries")
                        dom: 'lrtip'                // Remove the length drop-down (l), search box (f), and other elements as needed
                    });
                }
            },
            error: function () {
                $('#grid1 tbody').html('<tr><td colspan="5">Error loading data</td></tr>');
                $('#grid2 tbody').html('<tr><td colspan="5">Error loading data</td></tr>');
            }
        });
    }

    // Custom column filters
    $('#filterRoseName1').on('keyup', function () {
        $('#grid1').DataTable().columns(0).search(this.value).draw();
    });
    $('#filterRoseType1').on('keyup', function () {
        $('#grid1').DataTable().columns(1).search(this.value).draw();
    });
    $('#filterRoseColor1').on('keyup', function () {
        $('#grid1').DataTable().columns(2).search(this.value).draw();
    });

    $('#filterRoseName2').on('keyup', function () {
        $('#grid2').DataTable().columns(0).search(this.value).draw();
    });
    $('#filterRoseType2').on('keyup', function () {
        $('#grid2').DataTable().columns(1).search(this.value).draw();
    });
    $('#filterRoseColor2').on('keyup', function () {
        $('#grid2').DataTable().columns(2).search(this.value).draw();
    });
});

I have tried to use my 'getPageLength()' function (see below) to assign a value to my 'pageLength' property. Unfortunately, the function does not return the same number of rows at launch versus after a refresh.

    // Function to determine the number of rows to display based on screen size and row height
    function getPageLength() {
        var screenHeight = window.innerHeight; // Get the screen height
        var rowHeight = $('#grid1 tr').first().outerHeight(); // Get the height of a table row
        var headerHeight = $('grid1 thead').outerHeight(); // Get the height of the table header

        // Calculate available height for rows (subtract header height and any other margins/paddings)
        var availableHeight = screenHeight - headerHeight - 100; // 100px to account for margins, padding, etc.
        
        // Calculate the number of rows that fit in the available height
        var rowsPerPage = Math.floor(availableHeight / rowHeight);

        return rowsPerPage; // Return the number of rows to display
    }

Is it possible to have the same number of rows at launch and after a refresh?

Answers

Sign In or Register to comment.