Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable sorting on last column when using jQuery DataTables

I'm using jQuery DataTables in a project and I would like to know how to disable sorting for the last column. I want to implement this site-wide.

Right now I have the following code:

<!-- jQuery DataTable -->
    <script src="../assets/js/plugins/dataTables/jquery.datatables.min.js"></script>
    <script>
        /* Default class modification */
        $.extend( $.fn.dataTableExt.oStdClasses, {
            "sWrapper": "dataTables_wrapper form-inline"
        } );

        /* API method to get paging information */
        $.fn.dataTableExt.oApi.fnPagingInfo = function ( oSettings )
        {
            return {
                "iStart":         oSettings._iDisplayStart,
                "iEnd":           oSettings.fnDisplayEnd(),
                "iLength":        oSettings._iDisplayLength,
                "iTotal":         oSettings.fnRecordsTotal(),
                "iFilteredTotal": oSettings.fnRecordsDisplay(),
                "iPage":          Math.ceil( oSettings._iDisplayStart / oSettings._iDisplayLength ),
                "iTotalPages":    Math.ceil( oSettings.fnRecordsDisplay() / oSettings._iDisplayLength )
            };
        }

        /* Bootstrap style pagination control */
        $.extend( $.fn.dataTableExt.oPagination, {
            "bootstrap": {
                "fnInit": function( oSettings, nPaging, fnDraw ) {
                    var oLang = oSettings.oLanguage.oPaginate;
                    var fnClickHandler = function ( e ) {
                        e.preventDefault();
                        if ( oSettings.oApi._fnPageChange(oSettings, e.data.action) ) {
                            fnDraw( oSettings );
                        }
                    };

                    $(nPaging).addClass('pagination').append(
                        '<ul>'+
                            '<li class="prev disabled"><a href="#">&larr; '+oLang.sPrevious+'</a></li>'+
                            '<li class="next disabled"><a href="#">'+oLang.sNext+' &rarr; </a></li>'+
                        '</ul>'
                    );
                    var els = $('a', nPaging);
                    $(els[0]).bind( 'click.DT', { action: "previous" }, fnClickHandler );
                    $(els[1]).bind( 'click.DT', { action: "next" }, fnClickHandler );
                },

                "fnUpdate": function ( oSettings, fnDraw ) {
                    var iListLength = 5;
                    var oPaging = oSettings.oInstance.fnPagingInfo();
                    var an = oSettings.aanFeatures.p;
                    var i, j, sClass, iStart, iEnd, iHalf=Math.floor(iListLength/2);

                    if ( oPaging.iTotalPages < iListLength) {
                        iStart = 1;
                        iEnd = oPaging.iTotalPages;
                    }
                    else if ( oPaging.iPage <= iHalf ) {
                        iStart = 1;
                        iEnd = iListLength;
                    } else if ( oPaging.iPage >= (oPaging.iTotalPages-iHalf) ) {
                        iStart = oPaging.iTotalPages - iListLength + 1;
                        iEnd = oPaging.iTotalPages;
                    } else {
                        iStart = oPaging.iPage - iHalf + 1;
                        iEnd = iStart + iListLength - 1;
                    }

                    for ( i=0, iLen=an.length ; i<iLen ; i++ ) {
                        // Remove the middle elements
                        $('li:gt(0)', an[i]).filter(':not(:last)').remove();

                        // Add the new list items and their event handlers
                        for ( j=iStart ; j<=iEnd ; j++ ) {
                            sClass = (j==oPaging.iPage+1) ? 'class="active"' : '';
                            $('<li '+sClass+'><a href="#">'+j+'</a></li>')
                                .insertBefore( $('li:last', an[i])[0] )
                                .bind('click', function (e) {
                                    e.preventDefault();
                                    oSettings._iDisplayStart = (parseInt($('a', this).text(),10)-1) * oPaging.iLength;
                                    fnDraw( oSettings );
                                } );
                        }

                        // Add / remove disabled classes from the static elements
                        if ( oPaging.iPage === 0 ) {
                            $('li:first', an[i]).addClass('disabled');
                        } else {
                            $('li:first', an[i]).removeClass('disabled');
                        }

                        if ( oPaging.iPage === oPaging.iTotalPages-1 || oPaging.iTotalPages === 0 ) {
                            $('li:last', an[i]).addClass('disabled');
                        } else {
                            $('li:last', an[i]).removeClass('disabled');
                        }
                    }
                }
            }
        });

        /* Show/hide table column */
        function dtShowHideCol( iCol ) {
            var oTable = $('#example-2').dataTable();
            var bVis = oTable.fnSettings().aoColumns[iCol].bVisible;
            oTable.fnSetColumnVis( iCol, bVis ? false : true );
        };

        /* Table #example */
        $(document).ready(function() {
            $('.datatable').dataTable( {
                "sDom": "<'row'<'span6'l><'span6'f>r>t<'row'<'span6'i><'span6'p>>",
                "sPaginationType": "bootstrap",
                "oLanguage": {
                    "sLengthMenu": "_MENU_ records per page"
                }
            });
            $('.datatable-controls').on('click','li input',function(){
                dtShowHideCol( $(this).val() );
            })
        });
    </script>
like image 336
Psyche Avatar asked Aug 17 '12 15:08

Psyche


People also ask

How do I turn off sorting in columns?

To disable sorting for one column, select the name of this column in the list below Customize columns, and then de-select Make sortable: To deselect sorting for all columns, you'll first need to select all columns at once.

How do I sort a specific column in a DataTable?

The existing answers are using legacy DataTables syntax. Versions 1.10+ should use the following syntax: $('table'). dataTable({ "pageLength": -1, //display all records "order": [[ 0, "desc" ]] // Sort by first column descending });

What is FixedColumns in DataTables?

Description. FixedColumns provides the option to freeze one or more columns to the left or right of a horizontally scrolling DataTable. This allows information in the fixed columns to remain visible even when scrolling through the data set. This can be particularly useful if you wish to show a large number of columns.

What are the salient features of DataTables in jQuery?

DataTables will read all of the information about the table from the page (the DOM) and add features such as filtering, paging and sorting. This follows the basis for progressive enhancement where a table will be enhanced if JavaScript is available, and not if the browser doesn't have the required capabilities.


2 Answers

The aoColumnDefs' aTargets parameter lets you give indexes offset from the right (use a negative number) as well as from the left. So you could do:

aoColumnDefs: [
  {
     bSortable: false,
     aTargets: [ -1 ]
  }
]

The equivalent new API (for DataTables 1.10+) would be:

columnDefs: [
   { orderable: false, targets: -1 }
]
like image 76
Allan Jardine Avatar answered Oct 07 '22 06:10

Allan Jardine


I would like to develop the current answer.

The good way is to use aoColumnDefs as mentioned.
The default value for the bSortable parameter is true (for each column).

You've got 2 options...

By index :

var table = $('#example').DataTable({
   'aoColumnDefs': [{
        'bSortable': false,
        'aTargets': [-1] /* 1st one, start by the right */
    }]
});

By class :

var table = $('#example').DataTable({
   'aoColumnDefs': [{
        'bSortable': false,
        'aTargets': ['nosort']
    }]
});

Adding the class on the <th> :

<table>
    <thead>
        <tr>
            <th>Foo</th>
            <th>Bar</th>
            <th class="nosort">Baz</th>
        </tr>
    </thead>
    <tbody>...</tbody>
</table>

Documentation about columns

JSBin

like image 68
zessx Avatar answered Oct 07 '22 04:10

zessx