Keeping selected rows after executing ajax.reload()

Keeping selected rows after executing ajax.reload()

jLinuxjLinux Posts: 981Questions: 73Answers: 75

I have an AJAX sourced table that also has select enabled. When someone selects a row, then does something that triggers ajax.reload(), it will de-select the row.

I tried to use ajax.reload( null, false ), but that didn't seem to work.

Im really trying to avoid doing something like... keeping an array of selected rows (which gets updated everytime something is selected/deselected), then on ajax.reload(), re-select those rows. That would cause a "flicker" in the selects as well.

Thank you!

This question has an accepted answers - jump to answer

Answers

  • jLinuxjLinux Posts: 981Questions: 73Answers: 75
    edited October 2015

    This is the current work-around I have for it, which works, its just really... unorthodox

    $( document ).ready(function() {
        // Array to store the selected rows - Updated on select/deselect,
        // and referenced when table redraws
        var selected_rows = [];
    
        // Initialize DT
        $( '#data-table' ).DataTable( {
            select: {
                style: 'multi'
            },
            initComplete: function ( settings, json ) {
                manage_selects( this );
            }
        } );
    
        // Function to manage the selected rows, which need to be re-selected when the table is redrawn
        function manage_selects ( $dt ) {
            var $api = $dt.api();
    
            $api.on( 'select', function ( e, dt, type, indexes ) {
                // Add new selected ID to the selected_rows array
                selected_rows.push( indexes[ 0 ] );
            } );
    
            $api.on( 'deselect', function ( e, dt, type, indexes ) {
                // Remove the row that was deselected, using UnderscoreJS
                selected_rows = _.without( selected_rows, indexes[ 0 ] );
            } );
    
            $api.on( 'draw.dt', function () {
                // Select the rows again, since they are de-selected after the re-draw
                $api.rows( _.uniq(selected_rows) ).select();
            } );
        }
    });
    

    Basically, whenever rows are selected, it adds the row to the selected_rows array, and whenever rows are deselected, remove them from the array, then when the table is re-drawn, it selects the rows again.

    Good news is it seems to work without the "flicker" I was expecting, but I still think that theres gotta be a better way.

  • cipstercipster Posts: 1Questions: 0Answers: 1
    Answer ✓
  • jLinuxjLinux Posts: 981Questions: 73Answers: 75

    Thanks @cipster, I think I actually ended up using that.. Just forgot to update the thread :)

  • leandrosnxleandrosnx Posts: 1Questions: 0Answers: 0

    great!!!!

This discussion has been closed.