jqGrid - power to the people! (well, the nerds, anyway)

jqGrid - power to the people! (well, the nerds, anyway)

Filtering the jqGrid Programatically   

Added to Code by Richard.stokoe on Tuesday 5th July 2011

Today, I spent a stupid amount of time looking for the solution to a jqGrid problem. And I want to write the answer that worked here, on my interwebs, for posterity. Or until the bandwidth bill comes and I can't afford to renew.

Non-nerdy types may wish to look away now. Here be dragons anoraks.

So. I have a jqGrid on my webpage and it is called richGrid. This means I can grab hold of it through jQuery by using:


$("#richGrid")


If I want to reload 'richGrid', I can do this:


$("#richGrid").trigger("reloadGrid");


... and if I want to point it at a different data source, I can use the "new API", like this:


$("#richGrid").setGridParam("url", "http://www.otherdatasource.com");


And Robert is, indeed, your mother's brother.

But today I wanted to add a filter to my jqGrid programmatically. After some reading, I spotted a useful source which said that you can't append the filter to the URL, like above. Instead, you have to provide key/value pairs to the 'postData' property/parameter.

Easy, I thought. You just do...


$("#richGrid").setGridParam("postData", { myKey: "myValue" });


But did it work? No. Did it buggery heck.

After about three hours, I spotted somewhere under a rock that the following is the syntax that you need to programatically filter the jqGrid:


$("#richGrid").setGridParam({postData: {myKey: "myValue"}});


Of course it is.

But, don't forget the most important step. So far we've only supplied the postData key/value, we also need to reload it. Fortunately, the new jqGrid API is smart enough to allow chaining. So the following is perfectly adequate:


$("#richGrid").setGridParam({postData: {myKey: "myValue"}}).trigger("reloadGrid");


Marvellous.

Comments...