views:

1094

answers:

3

What is the best way to programmatically select all rows in a jqGrid that is set to multiselect?

The code could loop through all of the rows one-at-a-time and select each one, but then the checkbox in the grid header is not checked. I was thinking about just triggering the header row checkbox's clicked event, but that would make assumptions about the underlying jqGrid implementation. There must be a better way...

Thanks in advance!

+2  A: 

If you select all of the rows in a multiselect jqGrid by clicking on each one manually, the checkbox in the header doesn't get checked, so I wouldn't necessarily expect it to happen when you do it programmatically (if you use setSelected(rowid, true) for each row, it's the equivalent of clicking on each, as the "true" parameter indicates that the clicked event should be fired for each one).

So in fact, if you want all of them to get checked AND want the checkbox in the header to be checked, triggering the clicked event may be your best bet. If you dig into the source code and look at what happens when you click the checkbox, it is in fact just looping through all of the rows and setting each as selected, so I don't think you're going to do a lot better.

JacobM
Thanks for your time, it looks like I will just go with that approach then.
Justin Ethier
+1  A: 

Oddly, there doesn't seem to be such a function in the API. Programmatically selecting the "select all" checkbox will trigger the select all code (which you can find in grid.base.js, starting at line 1053. Unlike selecting the individual rows manually, this will correctly fire the onSelectAll event. So, yes, this makes assumptions, but not as many as the other way. :/

Craig Stuntz
You would think such a function would be part of the API - something to suggest for a future version, I suppose.
Justin Ethier
A: 

Yeah, it's true that this is not a very conventional approach, and is basically what you said you considered doing, but I found this was the easiest way to get all the rows selected and also have the header checkbox selected:

  var grid = $("#my_grid");
  grid.resetSelection();
  $('#cb_my_grid').click();
  var ids = grid.getDataIDs();
  for (var i=0, il=ids.length; i < il; i++ ) 
   grid.setSelection(ids[i], false);

I suppose the rows don't get selected when the header checkbox is programmatically clicked because of the jqGrid underlying implementation, like you said? I don't know the way it works underneath, but this seems to work for me on top for now.

The main reason I want to make sure the header checkbox gets selected in my grids is so the user can subconsciously determine that yes, all the rows in the grid are definitely selected right now (including ones not visible below the current scroll view), and not have to click the header checkbox just to make sure.

@Craig -- I'll have to try your method, it seems simpler and more reasonable

cwasden