rwkiii rwkiii - 4 months ago 197
jQuery Question

How to maintain jQuery DataTables scroll position after .draw()

I am using jQuery Datatables plugin for a smal table (12 rows). Some

<input type="text" ...
fields allow editing. When the input field loses focus I need to validate its value and possibly change the field value. I haven't been able to get modified input field values to be recognized by DataTables without issuing a
.draw()
afterwards, but this causes the table to scroll to the top of the table.

Is there a way of maintaining the current scroll position after issuing a .draw()?

$('#mytable').on('blur', 'input', function (e) {

var inputFieldId = this.id;
var inputFieldVal = $(this).val();

{ ... perform validation of field value ... }

$('#mytable').DataTable().rows().invalidate().draw();
});


EDIT

I saw someone trying to do the same thing I am and they indicated that the following code worked for them. This seems like a very simple way of accomplishing what I need, but I'm always getting scrollTop = 0 myself. Anyone see how I can get the row index of the currently selected row?

var scrollPos = $(".dataTables_scrollBody").scrollTop();
$('#mytable').DataTable().rows().invalidate().draw(false);
$(".dataTables_scrollBody").scrollTop(scrollPos);

Answer

I don't think you can do that, but you can use the Callback function instead:

$(document).ready(function() {
    var selected = [];

    $("#example").dataTable({
        "processing": true,
        "serverSide": true,
        "ajax": "scripts/ids-arrays.php",
        "rowCallback": function( row, data ) {
            if ( $.inArray(data.DT_RowId, selected) !== -1 ) {
                $(row).addClass('selected');
            }
        }
    });

    $('#example tbody').on('click', 'tr', function () {
        var id = this.id;
        var index = $.inArray(id, selected);

        if ( index === -1 ) {
            selected.push( id );
        } else {
            selected.splice( index, 1 );
        }

        $(this).toggleClass('selected');
    } );
} );

Ref : https://datatables.net/examples/server_side/select_rows.html