10 JQGrid Tips learned from my experience

For the past few days I have been working with JQGrid, one of the most powerful JQuery plug-in.  To give an outline, JQGrid helps us to create a grid with ease. The power of JQGrid comes from the fact that almost all the needs for a grid are addressed using simple tunable options. JQGrid can be downloaded from http://www.trirand.com/blog/?page_id=6.  JQGrid has a good documentation available at http://www.secondpersonplural.ca/jqgriddocs/index.htm. Also most of the JQGrid options are demonstrated well in http://www.trirand.com/jqgrid35/jqgrid.html. In spite of these well written documents, there are times I spent digging JQGrid source code for some customization needs. I also strongly feel that most of my co-workers might need the same at some point of time, so thought of blogging (documenting) for further reference.

All the code used in this article can be downloaded from here.

Our very first table looks as belowdraft-table

TIP 1: Changing JQGrid width and height

As depicted in the picture, the table doesn’t show up with paging information. Due to the smaller width, the 2nd column header and value are also not fully visible.  To solve this, we need to set the width of the table, thereby columns. This can be achieved as shown below

  1. During grid creation, use the property width with value in pixel as

width:700

OR

2. After grid creation, use setGridWidth(width, shrink) API as

$([tableid]).setGridWidth(700,true);

Similarly, height of the table can also be set using height :<value is pixel> and setGridHeight(height) API.  The default height is 150px. I am still searching for a way to set width/height of JQGrid in percentage (%). Comment, if you already know it.

TIP 2: Grid without unnecessary scroll area

If you are sure that the grid is not going to take more than N values and those N values can be fit in a single page, then there is no need for a scroll bar. In this case the space allotted for scrollbar is immaterial. I would rather prefer to remove this space. This can be achieved by setting the value of scrollOffset to zero as follows,

scrollOffset:0

By default the value of scrolloffset will be 18px
TIP 3:  Error due to missing locale file

You have included all the needed JS files like, JQuery, jqgrid (single file as minimized js/jquery.jqGrid.min.js) but still hitting with an error “$.jgrid is undefined” and grid is not rendered. This might be due to missing locale file. To solve this include appropriate locale, as

<script src="jqgridsrc/src/i18n/grid.locale-en.js" type="text/javascript" charset="utf-8"></script>

TIP 4: Callback function

We came across a requirement where we need to associate a hover event only to the first cell of a grid. To do the same, we need to get the first cell (td) and associate hover function on it and then implementing the functionality needed. Let’s assume that these functionalities (writing selector to get the first cell and writing .hover(…) function) is available in a function named doWhenHover(). The point here is when to call this function? THINK !! THINK !! THINK !!

If you told that it should be after the function that creates the table, in our example createMyTable(), then you are wrong.  Since the grid is not guaranteed to be completely formed at the end of createMyTable() function. So, JQGrid provides a callback function, loadComplete to which a function can be associated during grid creation like,


loadComplete: doWhenGridFullyLoaded

….

//grid creation completed

function doWhenGridFullyLoaded(){

//do the operation here

}

TIP 5: Using pagers only for buttons (or icons)

JQGrid documentation provides a tip at http://www.secondpersonplural.ca/jqgriddocs/index.htm under jqGrid > User Modules > Tips, Tricks and Hacks using which pager can be removed.  Here is yet another way to do the same. If you want to have pager only to add buttons and don’t like to display page numbers and other stuffs then we could remove those items as shown below,


$(‘#
<pagername>_center’).remove();

$(‘#
<pagername>_right’).remove();

Example: $('#mysimpletablepager_right').remove();

TIP 6: Hiding unwanted buttons in navigation bar

When navGrid(…) API is called to add a icon, say refresh  as


$(‘#
<tableid>’).navGrid('#mysimpletablepager',{refresh:true});

the following icons will be added in addition to the refresh icon

edit, add, del, refresh, search

To hide any of these icons associate those icons to a value of false. Say for example to hide edit, add icons and show other icons we can use the following fragment of code


$(‘#
<tableid>’).navGrid('#mysimpletablepager',{edit:false,add:false});

Also, by default view icon will be hidden, this can be made visible by associating true to it as view:true

Tip 7: Hiding the inline search by default

In addition to the popup search in JQGrid there is also an additional option of having inline search. In this case, a search textbox will be added to top of each column. Refer JQGrid documentation for the procedure to add inline search. But, when we add inline search functionality the search textbox will be shown by default and it occupies the first row below the header.  Though it can be argued that, showing search textbox by default makes the functionality explicit to user, I like it to be the other way i.e. when the grid is loaded the search textbox has to be hidden. User can make explicit request to show the search textbox. To do the same call mygrid[0].toggleToolbar() (the same code that is called when inline search icon is clicked) at the end of grid creation code as follows,


var myGrid = $(‘#mysimpletable’).jqGrid({

     url:<value>,

    ….//.other options

   })

.navButtonAdd("<
<pagerid>>",{caption:"",title:"Toggle Search Toolbar", buttonicon :'ui-icon-search', onClickButton:function(){ mygrid[0].toggleToolbar() } }); //icon to add the search bar with search textbox

mygrid.filterToolbar(); //adds the search toolbar

mygrid[0].toggleToolbar();//hide the toolbar by default

TIP 8: Having your own icons for navigation bar buttons

We are not always fulfilled with the available JQGrid/JQuery-UI images. So we might need to put our own image/icon for some of the buttons. This could be achieved by writing our own CSS and associating it with the navigator grid button by specifying it as a value to buttonicon as shown below


.ui-icon.myicon {

    width: 16px;

    height: 16px;

    background-image:url(edit.png);

}


mygrid.navButtonAdd("#mysimpletablepager",{caption:"",title:"Toggle Search Toolbar", buttonicon:'myicon', onClickButton:function(){ mygrid[0].toggleToolbar() } });

TIP 9: Removing title bar close button

I don’t find a real use of the tile bar close button. It would be much useful if the adjacent components occupy the space whenever user shrinks the grid, something like IGoogle portlets. Though JQGrid does it, it largely depends on the enclosing component. So I prefer to remove of button thereby hiding the functionality from user. As other removal this can also be easily achieved using remove() API as shown below


$('.ui-jqgrid-titlebar-close','#gview_mysimpletable').remove();

Note: Title bar won’t appear if the caption is an empty string.

TIP 10: Adding toolbar

JQGrid also provides an option to add toolbar to the table. This can be achieved using toolbar option, toolbar:[true,"both"] during grid creation. First parameter specifies whether the grid needs to be added or not. The second parameter is to tell about the location of the toolbar. Second parameter can take three values namely, top, bottom and both.

Stay tuned to know about the procedure for adding buttons to toolbar.

Version of

JQGrid - 3.5 beta

JQuery - 1.3.2

JQuery UI Theme - Dark Hive

Feel free to share your experience with JQGrid and also if you have cleaner way to solve some of the items discussed above, as comments.

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to TwitterAdd to TechnoratiAdd to Furl

About these ads

58 Responses

  1. Keep going…………..

    Expecting more from you… :)

  2. [...] to JQGrid toolbar Posted on July 14, 2009 by Veerabahu As I have wrote in my previous article, JQGrid is one of the most powerful JQuery plug-ins used in creation of grids. Though JQGrid [...]

  3. I have a fluid layout and i need a 100% width grid as you… i hope this will be possible soon

  4. Being a .Net developer I’ve worked most with server-side controls, namely Telerik. Recently I started using a JQuery plugin called DataTables which converts HTML tables to a datagrid.

    This is a different approach in that on the server I gen the “data” for the grid as … and DataTables is applied client side. A different approach to be sure. Given your posts on your blog, I’m going to experiment with jqGrid soon.

  5. jqgrid 3.5 support autowidth aka 100% width.
    just add autowidth: true

  6. Hi Veerabahu,

    Thanks for the great tutorial. I am really looking forward to using Jqgrid. But I can’t get the formatting for V3.5 to work right. I get a grid and lower pager no prob. But the theme and caption bar along with cell formatting is just plain. I have checked and checked dependencies. Any tips would be much appreciated.

    Thanks,

    Lance

  7. @lance any errors or mis-located css/js files. if you point to images depicting the current formatting then will be easier to comment more

  8. [...] 10 JQGrid Tips learned from my experience [...]

  9. really nice tips !! specially the close button one :) !

  10. Hi Veerabahu,

    I got it resolved. I found someone who had an example online that was working. It then found I had not referenced the right css etc.

    Thanks for the help and great tips!

    Lance

  11. Any idea of how to possibly add custom action icons to each row? I need to have the last row contain 3 icons, all of which are linked to an external page with an id as one of its post params.

    Possible?

  12. “Note: Title bar won’t appear if the caption is an empty string.”

    Nice tip. thanks.

  13. @Dan do you need to add custom icons to each row then you can refer to jqGrid Demos > Row Editing > Custom Edit. If the icons needed to be added to a row then you can pass those in JSON itself HTH

  14. Hi,

    I need to add column dynamically to the jqGrid, is that possible ?

    Thanks!

  15. @Wildan Maulana One way to make this work is by adding the column during creation time and hiding it. Showing the column only when needed. Will this work in your case ?

  16. No, it will not work,

    You can see the screenshoot mf my app on this address :

    http://wildanm.wordpress.com/2009/09/09/openthink-online-chart-creator/

    There is button for adding and removing selected column. Further, i want to be able
    to change the label of the selected column.

    Is that possible ? i’m new to jqGrid

  17. I don’t see a direct API to do this in jqGrid. But you can do DOM manipulation (when button is clicked) and do the same.
    For example the code
    $(‘#list2 tr’).append(“13″)
    will add a new column to the table shown in http://www.trirand.com/jqgrid/jqgrid.html > Loading Data > JSON Data.
    Note: You also need to do the same manipulation in th
    HTH. Let me know if you need any help !!

  18. Hai Veera, can you give me the code example plase ?

    Thanks!

  19. Great tips, I found your site trying to remove the scrollbar space that I didn’t need. As far as setting the height to 100%. As of the current version that property is a String.

    so you can set it with this.

    height: “100%”

    or if you want a pixel height

    height: “500px”

  20. hey, thanks !!

    tht was a great article :)

  21. Hi Veerabahu,

    Is taht any method to expand / collapse all the row in jqgrid? PLease give me guidence.

  22. Hi Veerabahu,

    Is that any method or property to expand / collapse all the row in jqgrid? PLease give me guidence.

    Thanks,
    Vijay

  23. Vijay, I don’t think a direct method is available. But this can be easily written by iterating through the available rows and invoking click event. This could be done when a hyper link is clicked on like Gmail has “Select All”

  24. Hi Veerabahu

    We can iterate but , what is the event which gets fired in jqgrid(i am new in jqgrid) when we click on expand…can u please get me two line of code. The exact problem is..

    I have this jqgrid having many hierarchical records.I have a button , on click of which I need all the rows to expand..I will be grateful if you just explain this with 2 lines of code.

    Thanks And Regards
    Bibhu

  25. Hi Veerabahu,

    Thanks for reply. I have tried the same by $(“img[src*='/Content/images/ui-icons_00498f_256x240.png/ui-icon-plus']:visible”).parent().click(); . But this is not working. Is this correct ? or Please give me some code to click the plus sympol in the grid.

    Thanks,
    Vijay.

  26. Hi,
    gr8 have this kind of help on jqgrid. Is there any way to customize the size of the window that is coming for advanced seach in jqgrid???

  27. Since you have an id to that div and table you will be able to do it, but as they are relatively positioned it will affect the overall look. If you want this across all your table, did you tried tuning CSS ?

  28. [...] general usage of the jqGrid, there is another useful resource I found here documenting another’s trials and tribulations with jqGrid. Tags: CodeIgniter, jqGrid, [...]

  29. [...] general usage of the jqGrid, there is another useful resource I found here documenting another’s trials and tribulations with jqGrid. VN:F [1.7.7_1013]please [...]

  30. Great list!

    Does anybody know if there is some way to change column widths after the grid has been created? I am trying to keep column widths in multiple grids in sync, so I have set up an event listener for resizeStop which works as expected, but setColProp doesn’t support setting the width, so I am kind of stuck. Is there a workaround?

    Thanks.

  31. // Get the width of a given percentage
    function getWidthInPct(percent){
    screen_res = ($(document).width())*0.99;
    col = parseInt((percent*(screen_res/100)));
    return col;
    }

  32. nice article…you can set height of jqgrid with css, you just need to define height of parent element to heigh:100% and then for grid also…for example if you set body to height 100%, just set jggrid wrapper to percentage you want()…

    cheers

  33. nice article.. keep going

  34. Thanks for sharing =]

  35. Hi

    I want to show grid with + , – icon in order to show the subgrid.
    I could achieve this by using subgrid = true option. However, i have one question. How to disable some of + icons and how to remove some of + icons because at the last of the grid i want to show the summary . I mean i want to show the total number of records etc. there i do not want the +,- icon

    Can you tell me how to achieve this.

  36. @Marko’s technique did not work for me. I have tried setting the parent element of the table as suggest, as well as the table itself, as well as passing a percent to the grid. None of them work.

  37. This sort of works:

    function getWidthInPct(percent){
    screen_res = ($(‘#parentDiv’).width())*0.99;
    col = parseInt((percent*(screen_res/100)));
    return col;
    }

    $enhancedDatatable.jqGrid({
    datatype: “local”,
    colNames:{!colNamesJson},
    ..
    width:getWidthInPct(100),

    });

  38. Hi Veera

    I have a jqGrid ina portlet. Is there any way i can control its width so that it should come out of the portlet…if it grid is bigger than the space available, it should get a scrollbar. Can u help please?

  39. just making it up for my typo…controlling the width of the grid, so that it should not come out of the portlet.

    Thanks

  40. PHP datagrid component using JQGrid (based on JQuery). This library can generate fully featured CRUD application in record time.

    1. include(“jqgrid.php”);
    2. $g = new jqgrid();

    3. $grid["caption"] = “My Sample Grid”; // set grid customizable params
    4. $g->set_options($grid);

    5. $g->table = “tags”; // db table for CRUD operations
    6. $out = $g->render(“my_grid_1″);

    This code will result in fully functional Jquery Grid (JqGrid) with

    * Add
    * Edit
    * Delete
    * Search
    * Auto-filter
    * Sort
    * Pagination
    * Export
    * Multiple Themes (ThemeRoller)
    * and almost all features available for FREE … which cost $449 on official commercial license.

    http://azgtech.wordpress.com/2010/08/01/jqgrid-php-datagrid-component-free/

  41. Hi,
    This is the cool stuff… I have one doubt in that its like i wanna change my grid row and column size dynamically based on the window size or browser size. Is there any way to achieve this. Please help me to sort it out.

  42. Hello

    would anyone please kindly answer to this question I have as I have read 1300 pages and still cant see the sample anywhere.

    Can any of those grid tools actually make up a table with pagination, sorting, filtering etc WITH data provided on the fly and NOT out of a static table on the Database? Think for example you have select list boxes and there is a table updating itself on an ajax basis in real time as you interact with the select boxes. You need to have that paginated. All I am seeing is that they work with static tables that are already populated on the database. I dont see how they can call that dynamic.

    thanks a lot

  43. Just wanted to thank you for writing this. I have referred to this blog at least 10 times in the past year of working with the jqGrid and ASP.NET MVC.

  44. [...] “10 JQGrid Tips learned from my experience” [...]

  45. its a great tutorial to start with… however i have a basic question if we can disable sorting on jqgrid header columns?? the requirement is that based on the user role we have to show the grid as editable or not editable.

  46. isnt there any property like ‘autohight’, so that i can set height 100% to its parent element !

  47. I am new in jqGrid. I installed jqGRid successfully, But I could not add Single field searching option in jqGrid. Can you help me in this reagard?? I need some sample code or tutorial .

    Foysal

  48. Thanks!!!

  49. pls help me to set the pagination in jqrid,default it shows file name in the Page box

  50. I needed the ability to have the grid automatically resize when the window resized.

    resizeGrid : function () {
    var tbl = this.offset();
    if (tbl) {
    // Set the width of the grid based on document height – left*2
    this.setGridWidth($(window).width()-tbl.left*2,true);
    this.setGridHeight($(window).height()-tbl.top,true);
    }
    }

    I added that into the class. Then in my document ready function I binded a resize function which includes a timer to call the resize event. I used a timer so that it wouldn’t try to fire as it is resizing, only after it was finished.

    $(window).resize( function () {
    clearTimeout(tmResize);
    tmResize=setTimeout(“$(‘#yourtableid’).resizeGrid()”,100);
    });

  51. Oh, and I simplified that example a bit. In my actual code, the setTimeout calls a function and in that function I clear the timeout after it runs.

  52. The grid does not load when included from another php script. I guess the inclusion of js, classes and jquery scripts have to follow a certain sequence.

    Tried several combinations and permutations with no luck.

  53. Great article..certainly saved me some time today =)

  54. TIP 9: Removing title bar close button

    $(“#grid”).jqGrid({

    hidegrid: false,

    });

  55. I have an editable grid. I need to navigate through rows using arrow button. Is there a way to do it.?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: