Mottie's Tablesorter Pager not updating on a page with multiple tables on tabs (Bootstrap/Laravel)

家住魔仙堡 提交于 2019-12-12 00:23:35

问题


I have successfully been able to implement Mottie's Tablesorter 2.0 with Pager and Filtering in my latest Laravel 5.1 project on views with just one table.

However, I have a page where I have set up a number of tabs using Bootstrap CSS. Note that I'm using Blade Templating Engine to include a partial PHP for each of the tabs and that I have also set up the Pager in a separate partial. This has worked correctly for all the other views where I show just one table for the page.

This is the code for the declaration of the tabs:

<div class="container-fluid">
    <div id="content">
        <ul id="tabs" class="nav nav-tabs" data-tabs="tabs">
            <li class="active"><a href="#datos" data-toggle="tab">Datos</a></li>
            <li><a href="#pasajeros" data-toggle="tab">Pasajeros</a></li>
            <li><a href="#productos" data-toggle="tab">Productos</a></li>
            <li><a href="#add-productos" data-toggle="tab">Añadir productos</a></li>
            <li><a href="#pagos" data-toggle="tab">Pagos</a></li>
            <li><a href="#pagos-realizados" data-toggle="tab">Pagos realizados</a></li>
            <li><a href="#mensajes" data-toggle="tab">Mensajería</a></li>
        </ul>

        <div id="my-tab-content" class="tab-content">

            @include('groups.partials.passengers')
            @include('groups.partials.addproducts')

            { other includes removed for clarity }
        </div>
    </div>
</div>

And inside each of those partials, I include a tablesorted page with a pager inside each of them:

<div class="tab-pane" id="add-productos">
<div class="table-responsive" style="width:auto;">
    <table id="products-not-associated-table" class="table table-striped tablesorter">

        @include('partials.pager')

        <thead>
        <tr>
            <th>Descripción</th>
            <th>Precio</th>
            <th>Stock</th>
            <th>Usado</th>
            <th>Proveedor</th>
            <th>Obligatorio</th>
            <th>Asociar al grupo</th>
        </tr>
        </thead>
        <tbody>
        @foreach($products_not_associated as $product_not_associated)
            <tr>
                <td>{{ $product_not_associated->description }}</td>
                <td>{{ $product_not_associated->price }}</td>
                <td>{{ $product_not_associated->stock }}</td>
                <td>{{ $product_not_associated->used_stock }}</td>
                <td>{{ $product_not_associated->provider_id->commercial_name }}</td>
                <td>{{ $product_not_associated->mandatory ? 'Sí' : 'No' }}</td>
                <td class="text-center">
                {{ some other laravel code removed for clarity }}
                </td>
            </tr>
        @endforeach
        </tbody>
    </table>
</div>

So my final page has a bunch of tables in them, each with their own Tablesorter pager inside. However, when I load the page all of the pagers load just the value for one of the tables, making it possible to only work with Tablesorter in one tab.

If, for example, the first table it loads has 6 elements, another table that might have 100+ elements would only show me the first 10 (10 being the default value per page) and not let me use the pager in any way.

This is my pager code:

<div class="pager control-group">
<i class="fa fa-fast-backward first"></i>
<i class="fa fa-backward prev"></i>
<span class="pagedisplay"></span>
<i class="fa fa-forward next"></i>
<i class="fa fa-fast-forward last"></i>
&nbsp;
<label for="selected">Por página: </label>
<select class="pagesize" title="Elementos por página">
    <option selected="selected" value="10">10</option>
    <option value="20">20</option>
    <option value="30">30</option>
    <option value="40">40</option>
</select>
&nbsp;
<label for="gotoPage">Ir a página: </label>
<select class="gotoPage" title="Escoja página"></select>

And this is my javascript code to sort all the tables in the site in the same way:

$(document).ready(function () {
    sortTable(".tablesorter");
});

function sortTable(selector, sortList) {
sortListParameter = [
    [0, 1],
    [1, 0],
    [2, 0]
];
if (sortList != null) {
    sortListParameter = sortList;
}
$(selector).tablesorter({
    theme: 'bootstrap',
    widthFixed: false,
    showProcessing: true,
    headerTemplate: '{content} {icon}',
    cancelSelection: true,
    dateFormat: "ddmmyyyy",
    sortMultiSortKey: "shiftKey",
    sortResetKey: 'ctrlKey',
    usNumberFormat: false,
    delayInit: false,
    serverSideSorting: false,
    ignoreCase: true,
    sortForce: null,
    sortList: sortListParameter,
    sortAppend: null,
    sortInitialOrder: "asc",
    sortLocaleCompare: false,
    sortReset: false,
    sortRestart: false,
    emptyTo: "bottom",
    stringTo: "max",
    initWidgets: true,

    widgets: ['columns', 'uitheme', 'filter', 'resizable', 'stickyHeaders'],
    widgetOptions: {
        resizable: true,
        resizable_addLastColumn: true,
        uitheme: 'bootstrap',
        columns_thead: true,
        filter_childRows: false,
        filter_columnFilters: true,
        filter_cssFilter: "tablesorter-filter",
        filter_functions: null,
        filter_hideFilters: false,
        filter_ignoreCase: true,
        filter_reset: null,
        filter_searchDelay: 300,
        filter_serversideFiltering: false,
        filter_startsWith: false,
        filter_useParsedData: false,
        saveSort: false
    },
    initialized: function (table) {
    },
    selectorHeaders: '> thead th, > thead td',
    selectorSort: "th, td",
    debug: true
}).tablesorterPager({
    container: $(".pager"),
    ajaxUrl: null,
    ajaxProcessing: function (ajax) {
        if (ajax && ajax.hasOwnProperty('data')) {
            // return [ "data", "total_rows" ];
            return [ajax.data, ajax.total_rows];
        }
    },
    output: '{startRow} a {endRow} ({totalRows})',
    updateArrows: true,
    page: 0,
    size: 10,
    fixedHeight: true,
    removeRows: false,
    cssNext: '.next',
    cssPrev: '.prev',
    cssFirst: '.first',
    cssLast: '.last',
    cssGoto: '.gotoPage',
    cssPageDisplay: '.pagedisplay',
    cssPageSize: '.pagesize',
    cssDisabled: 'disabled'
});
$.extend($.tablesorter.themes.bootstrap, {
    table: 'ui-widget ui-widget-content ui-corner-all',
    header: 'ui-widget-header ui-corner-all ui-state-default',
    icons: 'ui-icon',
    sortNone: 'ui-icon-carat-2-n-s',
    sortAsc: 'ui-icon-carat-1-n',
    sortDesc: 'ui-icon-carat-1-s',
    active: 'ui-state-active',
    hover: 'ui-state-hover',
    filterRow: '',
    even: 'ui-widget-content',
    odd: 'ui-state-default'
});
}

I have already tried implementing the pager code directly into each of the tabs to see if it would help, which it didn't. Following another question asked here, I tried to declare a sortTable() function without a lot of the options, but that didn't help either.

I'd appreciate a lot any kind of help with this problem. I'm guessing it has to do something with the way the data for the Pager should be loaded after entering each tab, probably with some kind of custom ajax function. I have tried following some suggestions in Mottie's Tablesorter documentation using customAjax functions but I didn't get that to work either, but that could very well be my fault.

Thanks a lot for your help.


回答1:


It appears that the issue is that the container option is pointing to all the pagers:

container: $(".pager")

If you have multiple tables, each with their own pager, you'll need to either give each pager a unique ID, or target each table/pager group separately. Maybe something like this:

$( '.tablesorter' ).each( function( indx ) {
    $(this)
        .tablesorter({
            /* tablesorter options here */
        })
        .tablesorterPager({
            container: $( '.pager' ).eq( indx )
            // ...
        });
});



回答2:


Thanks for pointing me in the right direction, Mottie. Since I didn't want to have to declare different scripts for every table, I added some changes following your directions.

I will share my approach to solving this problem, which makes everything work flawlessly now, in case anyone faces the same trouble.

It iterates through every tablesorter element and applies the sortTable method:

$(document).ready(function () {
    $(".tablesorter").each(function(){
        sortTable($(this));
    });

});

The sortTable() method, instead of working over a CSS selector now, works over a jQueryObject. And since I am including the pager just after the declaration of the table and before the element, I have to work with the parent.

The modified lines are the ones between asterisks:

**function sortTable(jQueryObject, sortList)** {
    sortListParameter = [[0, 1],[1, 0],[2, 0]];

    if (sortList != null) {
        sortListParameter = sortList;
    }

    **jQueryObject.tablesorter({**

        [options],

        widgets: ['columns', 'uitheme', 'filter', 'resizable', 'stickyHeaders'],

        widgetOptions: {
            [options]
        },

        initialized: function (table) { },
        selectorHeaders: '> thead th, > thead td',
        selectorSort: "th, td",
        debug: true

    }).tablesorterPager({
        **container: jQueryObject.parent().find(".pager"),**
        ajaxUrl: null,
        ajaxProcessing: function (ajax) {
            if (ajax && ajax.hasOwnProperty('data')) {
                 return [ajax.data, ajax.total_rows];
            }
        },
        [other options]
    });
    $.extend($.tablesorter.themes.bootstrap, {
        [options]
    });
}

Thanks a lot again for your help, Mottie!



来源:https://stackoverflow.com/questions/32621130/motties-tablesorter-pager-not-updating-on-a-page-with-multiple-tables-on-tabs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!