6

I've a jqGrid-based application, and I use loadonce: true in the grid option and sortable: true, sorttype: 'text in the colModel to allow client-side sorting on the data grid. However, I found that, once the data grid is re-sorted, the last selected row will no longer be highlighted. My question is, how to keep the selected row being highlighted across data resorting?

William X
  • 6,751
  • 6
  • 31
  • 50

1 Answers1

10

I prepared for you the small demo which keeps the row selection. In the demo I rewrote the code of selectionPreserver used in case of reloadGrid usage having additional parameters: $("#list").trigger("reloadGrid", [{current:true}]);. See the answer for details.

The demo saves the current selection inside of the onSortCol event handler and restore it inside of the loadComplete:

onSortCol: function () {
    saveSelection.call(this);
},
loadComplete: function () {
    restoreSelection.call(this);
}

How you see the usage is very simple and you can integrate it in your code. The implementation of the saveSelection and restoreSelection is the following:

var lastSelArrRow = [],
    lastScrollLeft = 0,
    lastSelRow = null,
    saveSelection = function () {
        var $grid = $(this);
        lastSelRow = $grid.jqGrid('getGridParam', 'selrow');
        lastSelArrRow = $grid.jqGrid('getGridParam', 'selrow');
        lastSelArrRow = lastSelArrRow ? $.makeArray(lastSelArrRow) : null;
        lastScrollLeft = this.grid.bDiv.scrollLeft;
    },
    restoreSelection = function () {
        var p = this.p,
            $grid = $(this);

        p.selrow = null;
        p.selarrrow = [];
        if (p.multiselect && lastSelArrRow && lastSelArrRow.length > 0) {
            for (i = 0; i < lastSelArrRow.length; i++) {
                if (lastSelArrRow[i] !== lastSelRow) {
                    $grid.jqGrid("setSelection", lastSelArrRow[i], false);
                }
            }
            lastSelArrRow = [];
        }
        if (lastSelRow) {
            $grid.jqGrid("setSelection", lastSelRow, false);
            lastSelRow = null;
        }
        this.grid.bDiv.scrollLeft = lastScrollLeft;
    };
Community
  • 1
  • 1
Oleg
  • 220,925
  • 34
  • 403
  • 798
  • Dear Oleg, thanks for your detailed answer! It's great! According to your comment, I found the root cause is that the grid will be re-loaded even the sorting is performed on the client side, and as such the selection should be restored programmatically. – William X Jul 31 '11 at 07:22