Table Sortable

A jquery plugin to sort and paginate data in table form
Star View Demo View on Github

Installation

Add script link to your html file. Make sure to add table-sortable.js after jquery.

<script src="../jquery.min.js"></script>
<script src="https://table-sortable.now.sh/table-sortable.js"></script>
                    

How to use TableSortable?

Create html markup where you want to render your table.
                        <div id="table-sortable"></div>
                    
JS: Basic Options
                        // script.js
var options = {
    data: [...],
    columns: {...},
    responsive: {
        1100: {
            columns: {...},
        },
    },
    rowsPerPage: 10,
    pagination: true,
};
var table = $('#table-sortable').tableSortable(options);

                    

Basic Example

                        
/** Data is an Array of Objects; i.e. JSON object */
var data = [
    {
        formCode: 531718,
        formName: 'Investment Form',
        fullName: 'Test User',
        appointmentDate: '13 March, 2017',
        appointmentTime: '1:30PM',
        phone: '9876543210',
    },
    {
        formCode: 531790,
        formName: 'Investment Form 2',
        fullName: 'Test User',
        appointmentDate: '12 March, 2017',
        appointmentTime: '1:35PM',
        phone: '9876543210',
    },
    {
        formCode: 531334,
        formName: 'Investment Form 3',
        fullName: 'Test User',
        appointmentDate: '10 March, 2017',
        appointmentTime: '1:40PM',
        phone: '9876543210',
    },
    {
        formCode: 5317,
        formName: 'Investment Form 4',
        fullName: 'Test User',
        appointmentDate: '17 March, 2017',
        appointmentTime: '1:20PM',
        phone: '9876543210',
    }
];

/** and column with  */
var columns = {
    formCode: 'Form Code',
    formName: 'Form Name',
    fullName: 'Full Name',
    appointmentDate: 'Appointment Date',
    appointmentTime: 'Appointment Time',
    phone: 'Phone',
};

var table = $('#table-sortable').tableSortable({
    data: data,
    columns: columns,
    rowsPerPage: 10,
    pagination: true,
});
                        
                    

Update rowsPerPage dynamically

                        
var table = $('#table-sortable').tableSortable({
    data: data,
    columns: columns,
    rowsPerPage: 10,
    pagination: true,
});

$('select').on('change', function() {
    table.updateRowsPerPage(parseInt($(this).val(), 10));
})
                        
                    

Update data with Ajax

                        
var table = $('#table-sortable').tableSortable({
    data: [],
    columns: columns,
    rowsPerPage: 10,
    pagination: true,
});

$.get(/* url */, function(data) {
    // Push data into existing data
    table.setData(data, null, true);

    // or Set new data on table, columns is optional.
    table.setData(data, columns);
})
                        
                    

Option: data

Type: array<object>

This option is used to set data in form of collection to table. Default is [].

                        
var table = $('#table-sortable').tableSortable({
    ...
    data: [
        {
            formCode: 5317,
            formName: 'Investment Form 4',
            fullName: 'Test User',
            appointmentDate: '17 March, 2017',
            appointmentTime: '1:20PM',
            phone: '9876543210',
        },
    ],
    ...
});
                        
                    

Option: columns

Type: object

Configure how many columns you want to show in table and what are their labels. Default is {}.

                        
var table = $('#table-sortable').tableSortable({
    ...
    columns: {
        formCode: 'Form Code',
        formName: 'Form Name',
        fullName: 'Full Name',
        appointmentDate: 'Appointment Date',
        appointmentTime: 'Appointment Time',
        phone: 'Phone',
    }
    ...
});
                        
                    

Option: searchField

Type: DOM Element | jQueryElement | HTMLElementString

Add search on table data. It will trigger table update with debounce of 0.4s. Default is null.

                        
var table = $('#table-sortable').tableSortable({
    ...
    searchField: '#searchField',
    ...
});
                        
                    

Option: rowsPerPage

Type: number

Configure number of rows display on per page. Default is 10.

                        
var table = $('#table-sortable').tableSortable({
    ...
    rowsPerPage: 10,
    ...
});
                        
                    

Option: pagination

Type: boolean

Show/hide page numbers for table. Default is true.

                        
var table = $('#table-sortable').tableSortable({
    ...
    pagination: true,
    ...
});
                        
                    

Option: sorting

Type: boolean | array<string>

Enable/disable sorting on all columns or specific column. Default is true.

                        
var table = $('#table-sortable').tableSortable({
    ...
    sorting: true,
    ...
});

/* or on specific columns */

var table = $('#table-sortable').tableSortable({
    ...
    sorting: ['column1', 'column2'],
    ...
});
                        
                    

Option: formatCell

Type: function

Format individual cell, create your own styles. It takes a function whoes first argument is row-data(object) and second argument is column key. Default is null.

                        
var table = $('#table-sortable').tableSortable({
    ...
    formatCell: function(row, key) {
        if (key === 'formCode') {
            return $('<span></span>').addClass('font-weight-bold').text(row[key]);
        }
        if (key === 'fullName') {
            return $('<span></span>').addClass('text-uppercase').text(row[key]);
        }
        // Finally return cell for rest of columns;
        return row[key];
    },
    ...
});
                        
                    

Option: formatHeader

Type: function

Format individual header column, create your own styles. It takes a function whoes first argument is column value, second argument is column key, third argument is index. Default is null.

                        
var table = $('#table-sortable').tableSortable({
    ...
    formatHeader: function(columnValue, columnKey, index) {
        if (columnKey === 'formCode') {
            return $('<span></span>').addClass('bold').text(columnValue);
        }
        if (columnKey === 'fullName') {
            return $('<span></span>').addClass('uppercase').text(columnValue);
        }
        // Finally return columnValue;
        return columnValue;
    },
    ...
});
                        
                    

Option: totalPages

Type: number

Define total number of pages if you are using pagination on server. Default is 0.

                        
var table = $('#table-sortable').tableSortable({
    ...
    totalPages: 100,
    ...
});
                        
                    

Option: sortingIcons

Type: object

Change sorting icon on columns. Default is { asc: '<span>▼<span>', desc: '<span>▲</span>' }.

                        
var table = $('#table-sortable').tableSortable({
    ...
    sortingIcons: {
        asc: '<span>▼</span>',
        desc: '<span>▲</span>',
    },
    ...
});
                        
                    

Option: nextText

Type: string | HTMLElement | jQueryElement

Change pagination next button text. Default is <span>next<span>.

                        
var table = $('#table-sortable').tableSortable({
    ...
    nextText: '<span>next<span>',
    ...
});
                        
                    

Option: prevText

Type: string | HTMLElement | jQueryElement

Change pagination prev button text. Default is <span>prev<span>.

                        
var table = $('#table-sortable').tableSortable({
    ...
    prevText: '<span>prev<span>',
    ...
});
                        
                    

Option: onPaginationChange

Type: function

Callback function called whenever clicked on any button in pagination. First argument is clicked button page number and second argument is previous page number. Default is null.

                        
var table = $('#table-sortable').tableSortable({
    ...
    onPaginationChange: function(nextPage, setPage) {
        // Call api to get data for nextPage. And finally update table data;
        $.get(/* url */, function(data) {
            setPage(nextPage, data);
        })
    },
    ...
});
                        
                    

Option: responsive

Type: object

Render different table based on viewport width. It takes max-width as viewport value. Default is {}.

                        
var table = $('#table-sortable').tableSortable({
    ...
    responsive: {
        // It works for 571 - 1100 viewport width; (max-width: 1100px and min-width: 571px);
        1100: {
            // Other options
            columns: {
                formCode: 'Form Code',
                formName: 'Form Name',
            },
        },
        // It works for 0 - 570 viewport width; (max-width: 570px);
        570: {
            // Other options
            columns: {
                formName: 'Form Name',
            },
        }
    },
    ...
});
                        
                    

Option: tableWillMount

Type: lifecycle function

This function is called before rendering of table into DOM. Default is function.

                        
var table = $('#table-sortable').tableSortable({
    ...
    tableWillMount: function() {

    },
    ...
});
                        
                    

Option: tableDidMount

Type: lifecycle function

This function is called after rendering of table into DOM. Default is function.

                        
var table = $('#table-sortable').tableSortable({
    ...
    tableDidMount: function() {

    },
    ...
});
                        
                    

Option: tableWillUpdate

Type: lifecycle function

This function is called before any change is going to update into DOM. Default is function.

                        
var table = $('#table-sortable').tableSortable({
    ...
    tableWillUpdate: function() {

    },
    ...
});
                        
                    

Option: tableDidUpdate

Type: lifecycle function

This function is called after changes are applied DOM. Default is function.

                        
var table = $('#table-sortable').tableSortable({
    ...
    tableDidUpdate: function() {

    },
    ...
});
                        
                    

Option: tableWillUnmount

Type: lifecycle function

This function is called before table is removed from DOM. Default is function.

                        
var table = $('#table-sortable').tableSortable({
    ...
    tableWillUnmount: function() {

    },
    ...
});
                        
                    

Option: tableDidUnmount

Type: lifecycle function

This function is called after table is removed from DOM. Default is function.

                        
var table = $('#table-sortable').tableSortable({
    ...
    tableDidUnmount: function() {

    },
    ...
});
                        
                    

Property: constructor

Type: constructor function

Create a new instance of TableSortable. Default is function.

                        
var table = new TableSortable({
    element: '#root',
    data: [...],
    options: {...}
})
                        
                    

Property: options

Type: object

Get all table options. Default is {}.

                        
var table = $('#root').tableSortable({...});
console.log(table.options);
                        
                    

Property: _rootElement

Type: jQueryElement

Get rootElement where table is rendered. Default is jQueryElement.

                        
var table = $('#root').tableSortable({...});
console.log(table._rootElement);
                        
                    

Property: _dataset

Type: Dataset class instance

This property is used to store table data, which provides methods to get and sort data. Default is object.

                        
var table = $('#root').tableSortable({...});
console.log(table._dataset);
                        
                    

Dataset APIs

Add Data: _dataset.fromCollection()

Type: function

                        
table._dataset.fromCollection([{...}, {...}]);
                        
                    

Get Data:

  • _dataset.top(number)
  • _dataset.bottom(number)
  • _dataset.get(number, number)
                        
// Get top ten rows from collection
table._dataset.top(/* length */ 10);

// Get bottom ten rows from collection
table._dataset.bottom(/* length */ 10);

// Get rows from range
table._dataset.get(/* from */ 10, /* to */ 15);
                        
                    

Sort Data: _dataset.sort(string, string)

Type: function

                        
var sortDirection = table._dataset.sortDirection;

// Ascending order
table._dataset.sort(column_name, sortDirection.ASC);

// Descending order
table._dataset.sort(column_name, sortDirection.DESC);
                        
                    

Property: _pagination

Type: object

Get current page number and total pages. Default is object.

                        
var table = $('#root').tableSortable({...});

console.log(table._pagination);
// { elm: jQueryElement, currentPage: number, totalPages: number, visiblePageNumbers: number, }
                        
                    

Property: refresh

Type: function

Refresh will unmount table and rebuild again. It takes an argument to hardRefresh the table. Default is function.

                        
var table = $('#root').tableSortable({...});

table.refresh(); // It will update the table, if you have updated options they will be applied.
table.refresh(true); // It will distroy and create table from start.
                        
                    

Property: distroy

Type: function

Distroy will unmount table and remove table form DOM along with pagination. Default is function.

                        
var table = $('#root').tableSortable({...});

table.distroy();
                        
                    

Property: getData

Type: function

Get table data. Default is function.

                        
var table = $('#root').tableSortable({...});

table.getData();
                        
                    

Property: setData

Type: function

Set new data on table. First argument is array of object, second arguments is object to set columns (optional) and third argument is boolean to add in existing data (optional). Default is function.

                        
var table = $('#root').tableSortable({...});

// Set new data and columns on table
table.setData(data, columns /* optional */);

// Add data in existing data
table.setData(partialData, null, true);
                        
                    

Property: lookUp

Type: function

Implement external search or filter on table. First argument for the method is search string and secound argument is array of columns, it is optional. By default it lookup in all visible columns. Default is function.

                        
var table = $('#root').tableSortable({...});

table.lookUp('search string', /* optional */ ['column1', 'column2', 'column3']);
                        
                    

Property: getCurrentPageData

Type: function

Get data on current page. Default is function.

                        
var table = $('#root').tableSortable({...});

table.getCurrentPageData();
                        
                    

Property: updateRowsPerPage

Type: function

Update rows per page dynamically. Default is function.

                        
var table = $('#root').tableSortable({...});

table.updateRowsPerPage(20);