Search code examples
javascriptjquerytablesorter

Custom page splitter in pager for TableSorter


I am using the tablesorter to pagify some of my tables.

Is it possible (or in anyway easy to implement a way) for the pages to be by month or year? E.g. instead of the regular pages < |1| 2 3 4 5 > to have < |01-2014| 02-2014 03-2014 >


Solution

  • I think the easiest solution would be to use the filter widget (demo):

    HTML

    <div class="pager">
        <a href="#" class="prev">&lt;</a> |
        <a href="#" data-column="1" data-filter="1/1/2014 - 2/1/2014 0:00 am">1-2014</a> |
        <a href="#" data-column="1" data-filter="2/1/2014 - 3/1/2014 0:00 am">2-2014</a> |
        <a href="#" data-column="1" data-filter="3/1/2014 - 4/1/2014 0:00 am">3-2014</a> |
        <a href="#" data-column="1" data-filter="4/1/2014 - 5/1/2014 0:00 am">4-2014</a> |
        <a href="#" data-column="1" data-filter="5/1/2014 - 6/1/2014 0:00 am">5-2014</a> |
        <a href="#" data-column="1" data-filter="6/1/2014 - 7/1/2014 0:00 am">6-2014</a> |
        <a href="#" data-column="1" data-filter="" class="active">all</a> |
        <a href="#" data-column="1" class="next">&gt;</a>
    </div>
    

    Script

    var $table = $('table').tablesorter({
        theme: 'blue',
        widgets: ['zebra', 'filter'],
        widgetOptions: {
            filter_columnFilters: false
        }
    });
    
    $('.pager').find('[data-filter]').on('click', function () {
        var $this = $(this).addClass('active'),
            query = [];
        $this.siblings().removeClass('active');
        // set selected filter
        query[ $this.data('column') ] = $this.data('filter');
        $.tablesorter.setFilters($table, query, true);
    });
    
    $('.next, .prev').on('click', function () {
        var $a = $('.pager').find('a[data-filter]'),
            current = $a.index($a.filter('.active')),
            // add/subtract one to get to next; -1 wraps to last
            next = current + ($(this).hasClass('next') ? 1 : -1);
        // wrap last back to first
        next = next >= $a.length ? 0 : next;
        $a.eq(next).click();
    });