Put new rows at the specific position of the jQuery datatable

Put new rows at the specific position of the jQuery datatable

jezraeljezrael Posts: 2Questions: 1Answers: 0

DEFAULT
I create ajax datatable, which rows are sometimes filled by json in the end of table: jsfiddle and sometimes in the top of table. It depends of time of ajax response.

FIRST SOLUTION
I have to add first column containing a number and sort the datatable descending by it - jsfiddle. I can hide first column jsfiddle, but I rather use custom function.

var t = $("#tab1").DataTable({
    "ajax": "data1.json",
    columnDefs: [
         { className: "hide", "targets": [ 0 ] },
         ], 
    "columns": [
        { "data": "id"},
        { "data": "cat1"},
        { "data": "cat2"},
        { "data": "cat3"}
    ]
});

$.ajax({
    type: "GET",
    url: "data2.json",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (response) {
        t.rows.add(response.data); 
        t.draw();
    }
  });

IDEA - CUSTOM FUNCTION
I try to create custom function rows.addinposition(rows, position), but it works as function rows.add().
I copied and modified function rows.add found in jquery.dataTables.js at line 7879, I changed out.push() to out.splice() splice docs.

I know, it is not recommended, better is extend datatables api...

_api_register( 'rows.addinposition()', function ( rows, position ) {
    var newRows = this.iterator( 'table', function ( settings ) {
            var row, i, ien;
            var out = [];

            for ( i=0, ien=rows.length ; i<ien ; i++ ) {
                row = rows[i];

                if ( row.nodeName && row.nodeName.toUpperCase() === 'TR' ) {
                    //ROWS.ADD USE OUT.PUSH
                    //out.push( _fnAddTr( settings, row )[0] );
                    //CHANGED TO OUT.SPLICE
                    out.splice( position, 0, _fnAddTr( settings, row )[0] );
                }
                else {
                    out.splice( position, 0, _fnAddData( settings, row ) );
                }
            }
            console.log(out);
            return out;

        }, 1 );

    // Return an Api.rows() extended instance, so rows().nodes() etc can be used
    var modRows = this.rows( -1 );
    modRows.pop();
    modRows.push.apply( modRows, newRows.toArray() );

    return modRows;
} );    

It would be great if you could help me.

I found similar question:

datatables forum link - old version, no answer (I think)

Answers

  • jezraeljezrael Posts: 2Questions: 1Answers: 0
    edited July 2015

    I found one solution (thanks davidkonrad), but when I test it in jsdiddle I found 2. problems:

    1. ordering is wrong (2.,1.), not 1.,2.
    2. sometimes randomly added rows are on top of table, sometimes in 3. position.

    CODE:

        jQuery.fn.dataTable.Api.register('row.addByPos()', function(data, index) {     
            var currentPage = this.page();
    
            //insert the row 
            this.row.add(data);
    
            //move added row to desired index
            var rowCount = this.data().length-1,
                insertedRow = this.row(rowCount).data(),
                tempRow;
    
            for (var i=rowCount;i>=index;i--) {
                tempRow = table.row(i-1).data();
                this.row(i).data(tempRow);
                this.row(i-1).data(insertedRow);
            }     
    
            //refresh the current page
            this.page(currentPage).draw(false);
        });
    

    The above function (or plugin) inserts the row, and then "moves" the row up to its desired position simply by swapping content.
    jsfiddle demo

    Since the plugin add a function to the general API, the plugin should be declared before initialization of any dataTable using that function.

    { plugin declaration }
    var table = $("#example").DataTable();
    table.row.addByPos([data], 1);
    
  • allanallan Posts: 61,438Questions: 1Answers: 10,049 Site admin

    Position in a DataTable is entirely based upon the ordering conditions applied to the table. So if you want to insert a row at a particular point, either the data in it needs to cause it to be inserted at that point, or the ordering function applies to the table needs to put it into the required position (or perhaps a bit of both!).

    Having said that your plug-in API method of swapping the data around for the rows is cunning - I like that. Although you should be aware that the ordering applied to the table (if there is ordering, I'm guessing not in this case) would still cause them to appear in their correctly ordered positions.

    Allan

This discussion has been closed.