Search code examples
javascriptjqueryweb-applicationsdatatables

Datatables jquery plugin - limit number of selectable rows


When row selection is enabled on a datatable, is there way to limit the number of rows a user can select? I only want users to be able to select a maximum of two rows and a minimum of one in the datatable, but I don't see an option in the Datatables API that describes how to do this?

Will I need to perform this manually in some callback that's triggered whenever a user selects a row? I'd like to avoid this if possible. Any help or insight is appreciated.


Solution

  • Ok got an implementation working, so what I ended up doing was instead of limiting the number rows a user can select, I added some logic to deselect any previously selected row whenever a user clicked on another row. I treated the selection order as a queue, which I just implemented using an array, each time I push a new row to the queue, any previous element would get popped.

    The size of the queue determines the number of rows a user can select, by setting the queue size to two, this allows up to two rows to be selected, when an additional row is selected, the first selected row is removed from the queue. I used the fnGetInstance() and fnDeselect() functions below for deselecting rows from my data table instance

    //oldRow = first selected row from queue
    
    var oTT = TableTools.fnGetInstance( 'MyDataTable' );
    oTT.fnDeselect( oldRow );