6

I have a jqGrid on a page and users can click a button to add a new row. If there are already enough rows on the page to fill the visible portion of the grid the new row is added and a scroll bar appears but the user needs to scroll to see the new row.

Is there a way to do this programmatically?

3 Answers 3

11

A quick and easy way to do this using the jqGrid API is to:

  • Call editRow (which will set focus to the edited row)
  • And then immediately call restoreRow (because you do not really want to edit the row)

Otherwise you should be able to use jQuery's focus function to set focus to the row, for example: jQuery("#" + row_id).focus() - but I have not tested this method, so YMMV.

Actually focus will not scroll the grid's div. But you can use the following code to guarantee that the grid scrolls such that the row with a given id is viewable:

function getGridRowHeight (targetGrid) {
    var height = null; // Default

    try{
        height = jQuery(targetGrid).find('tbody').find('tr:first').outerHeight();
    }
    catch(e){
     //catch and just suppress error
    }

    return height;
}

function scrollToRow (targetGrid, id) {
    var rowHeight = getGridRowHeight(targetGrid) || 23; // Default height
    var index = jQuery(targetGrid).getInd(id);
    jQuery(targetGrid).closest(".ui-jqgrid-bdiv").scrollTop(rowHeight * index);
}
2
  • Actually, I do want to edit the row so I'll just leave it in edit mode - works like a charm! Mar 31, 2010 at 3:27
  • Thanks Justin! the only modification that i should do is .scrollTop( (rowHeight * index)-rowHeight) to make viewable the target row. Regards.
    – nerdcoder
    Dec 14, 2011 at 3:48
1
//i. Set newly added row (with id = newRowId) as the currently selected row
$('#myGrid').jqGrid('setSelection', newRowId);
//ii. Set focus on the currently selected row
$("#" + $('#myGrid').jqGrid('getGridParam', 'selrow')).focus();
0
-1

FYI:

I found this example helpful. http://gurarie.org/jqGrid.html from this post, http://www.trirand.com/blog/?page_id=393/bugs/setselection-is-not-scrolling-to-the-selected-row

My issue was $(tableInstance).jqGrid('setSelection', id) didn't work even scrollrows: true when height: 'auto' in jqGrid config. I set height to a specific height 20 and 'setSelection' worked. The selected row was in view for the user. Super Cool

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.