jQuery DataTables: Row reordering

Update
September 10, 2015
With jQuery DataTables 1.10.8 release there is now official RowReorder extension, see this example for demonstration. It is recommended to use RowReorder extension instead of the add-on mentioned in this article.

Solution

Reading comments on the project page I found modified source code of the plug-in by legrand….@gmail.com that fixes compatibility issues with DataTables 1.10.

Using that source code as a start I forked the add-on on github and added support for DataTables 1.10.

Demo

# Name Position Office Extn. Start date Salary
Name Position Office Extn. Start date Salary
$(document).ready(function(){
   var table = $('#example').DataTable({
      'ajax': {
         'url': '/lab/articles/jquery-datatables-row-reordering/ids-arrays.txt' 
      },
      'createdRow': function(row, data, dataIndex){
         $(row).attr('id', 'row-' + dataIndex);
      }    
   });
   
   table.rowReordering();
});

In addition to the above code, the following Javascript library files are loaded for use in this example:

//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js
//cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js
//code.jquery.com/ui/1.11.4/jquery-ui.min.js
//mpryvkin.github.io/jquery-datatables-row-reordering/1.2.2/jquery.dataTables.rowReordering.js

The following CSS library files are loaded for use in this example to provide the styling of the table:

//cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css

Edit on jsFiddle

Usage

Table structure

  • Table must be properly formatted according to the DataTables requirements e.g. it must have THEAD, TBODY and optionally TFOOT sections
  • Each TR element must have id attribute.
  • One column in the table should be indexing column.

Limitations

  • Rows can be ordered only by indexing column. This plugin will force ascending sorting by indexing column.
  • Sorting by columns will be disabled. If you shuffle rows in some order other than indexing column order there will be no way to determine to what position row is dropped.

Notes

Allan Jardine, creator of DataTables, is working on a new RowReorder plug-in for upcoming release of DataTables 1.10.8. Once DataTables 1.10.8 and RowReorder plug-in are out, I will write an article about it and will recommend using it instead of the plug-in mentioned in this article.

You May Also Like

Comments

  1. Thanks for this plugin port.
    I followed your fiddle and this tutorial but while I can drag rows of the table, the items return back to their original place as soon as mouse is released.

    Here’s my table initialization:

    var table;
    function draw_ordered_items_table(data) {
        table = $('#ordered_items_table').DataTable({
            "data": data,
            "paging": false,
            "lengthChange": false,
            "searching": false,
            "ordering": false,
            "info": false,
            "createdRow": function(row, data, dataIndex){
             $(row).attr('id', 'row-' + dataIndex);
          },
        table.rowReordering();
        });
    }
    

    Any reason why this could be ?

    I am using the same CDN as you have used in the jsFiddle for DataTables and jQuery UI. I just didn’t understand what you mean when you say that “One column in the table should be indexing column.”

    I see your table has a numbering column as the first column where as mine doesn’t have. So does that matter?

      1. Hi Michael, I have also followed your post. And, I encountered the same result while I drag a row item, the item returns back to the original place. I have set one of the columns as the row index in sequential order, but still the item returned back to the original location.

        This is my script

        $(document).ready(function () {
                var oTable = $("#tblFile").DataTable({
                    "iDisplayLength": 10,
                    "bServerSide": true,
                    "sAjaxSource": "@Url.Content("PlayListFilesAjaxHandler")",
                    "bProcessing": false,
                    "bStateSave": true,
                    "ordering": true,
                    //"rowReorder": true,
                    "createdRow": function(row, data, dataIndex){
                        $(row).attr('id', 'row-' + dataIndex);
                    },
                    "aoColumns": [
                        {
                            "sName": "id",
                            "bSearchable": false,
                            "bSortable": false,
                            "sWidth": '10%'
                        },
                        {
                            "sName": "FileName",
                            "bSearchable": false,
                            "bSortable": false,
                            "sWidth": '25%'
                        },
                        {
                            "sName": "FilePath",
                            "bSearchable": false,
                            "bSortable": false,
                            "sWidth": '50%'
                        },
                        {
                            "sName": "Action",
                            "bSearchable": false,
                            "bSortable": false,
                            "sWidth": '15%',
                            "render": function (data, type, full, meta) {
                                return '<a href="FileDelete/' + full[3] + '" rel="nofollow">Delete</a>';
                            }
                        }
                    ]
                });
        
                oTable.rowReordering();
            });
        
        1. I even used the exact version of .js and .css libraries mentioned in your post.

          What could have been missing in my DataTable initialization?

          1. Did anyone managed to find a solution for this ? I have the same problem, with an indexed column still doesn’t work 🙁

  2. HTML dynamic table using JavaScript. How can I find the each row data , when we click on check box?

            debugger;
            var flag = 0;
            var pdf;
    
            $(document).ready(
                function GetData() {
                    $.ajax({
                        type: "POST",
                        data: "{}",
                        url: "http://localhost:54402/OrderServices.asmx/getProducts1",
                        contentType: "application/json",
                        dataType: "json",
                        async: false,
                      //  success: functionToCallWhenSucceed
                        success: function (data) {
                            pdf = (data.d);
                            //alert(pdf);
                            var productt = pdf;
                            
                        var trHTML = '';
                        $.each(productt, function (index, item) {
                           
                            trHTML += '' + item.ItemName + '' + item.Brand + '' + item.Size + '' + item.Colour + '' + item.ResalerPrice + '';
                        });
    
                        $('.checkbox1').on('change', function () {
                            var bool = $('.checkbox1:checked').length === $('.checkbox1').length;
                            $('#checkAll').prop('checked', bool);
                        });
    
                        $('#checkAll').on('change', function () {
                            $('.checkbox1').prop('checked', this.checked);
                        });
    
    
    
                        var checkedRows = [];
    
                        $('#myTableData').on('check.bs.table', function (index, row) {
                            checkedRows.push({ id: row.id, name: row.name, forks: row.forks });
                            console.log(checkedRows);
                        });
    
                        $('#myTableData').on('uncheck.bs.table', function (e, row) {
                            $.each(checkedRows, function (index, value) {
                                if (value.id === row.id) {
                                    checkedRows.splice(index, 1);
                                }
    
                            });
                            console.log(checkedRows);
                        });
    
    
                        $("#add_cart").click(function () {
                            $("#output").empty();
                            $.each(checkedRows, function (index, value) {
                                $('#output').append($('').text(value.id + " | " + value.name + " | " + value.forks));
                            });
                        });
                        $('#myTableData').append(trHTML);
                    }
                    })
                    
                })
    

Leave a Reply

(optional)

This site uses Akismet to reduce spam. Learn how your comment data is processed.