Skip to content

Grid Appearance FAQs

Grid Appearance FAQs

Q) I upgraded to licensed version. Why i am having 'Free Version' tag line with grid?

Try following steps.

1) Please make sure you have replaced lib/js folder with the one in licensed packgage.

2) Your browser is using cached JS files. Try after clearing browser cached files. You can also try opening it in different browser OR browser's incognito mode.

^ Top

Q) How to show horizontal scroll bar in grid (when there are many columns) ?

You need to set following params:

$grid["autowidth"] = false;
$grid["responsive"] = false;
$grid["shrinkToFit"] = false; // dont shrink (or extend) to fit in grid width
$grid["width"] = "600";
...
$g->set_options($grid);

For 2.6.2+,

$grid["cmTemplate"]["visible"] = "xs+"; // show all column on small screens
$grid["shrinkToFit"] = false; // enable horizontal scrollbar
...
$g->set_options($grid);

If you dont specify the width property, it will be the sum of all columns width. To make scroll bar visible, the sum of column width must increase window width.

^ Top

Q) Change font size & height of cell

Update following css classes to change presentation.

<style>
.ui-jqgrid {font-size:14px; font-family:"tahoma";}
.ui-jqgrid tr.jqgrow td {height: 25px; padding:0 5px !important;}
</style>

^ Top

Q) How to show vertical lines for each column?

You can add following CSS code to show vertial lines in datagrid.

<style>
.ui-jqgrid tr.ui-row-ltr td { border-right-style:inherit !important; }
.ui-jqgrid tr.ui-row-rtl td { border-left-style:inherit !important; }
</style>

^ Top

Q) How to do word-wrap (fit) content in grid cells?

Update following css in page to change cell wrapping.

<style>
.ui-jqgrid tr.jqgrow td
{
    vertical-align: top;
    white-space: normal !important;
    padding:2px 5px;
}
</style>

To make word wrapping in view record dialog, add following css:

<style>
.ui-jqdialog-content .CaptionTD
{
    vertical-align: top;
}

.ui-jqdialog-content .form-view-data
{
    white-space: normal;
}
</style>

Also check this link for frozen columns with cell wrap. http://stackoverflow.com/questions/8686616/how-can-i-get-jqgrid-frozen-columns-to-work-with-word-wrap-on

^ Top

Q) How can i add caption along with icons of add,edit,delete.

You can set it using following config on jqgrid() object. For example:

$grid->navgrid["param"]["addtext"] = "Add Invoice";
$grid->navgrid["param"]["edittext"] = "Edit Invoice";
$grid->navgrid["param"]["deltext"] = "Delete Invoice";
$grid->navgrid["param"]["searchtext"] = "Search";
$grid->navgrid["param"]["refreshtext"] = "Refresh";
$grid->navgrid["param"]["viewtext"] = "View Invoice";

Altenrate, You need to put following additional JS and CSS code. You can change 'Add User' with your desired caption.

<script type="text/javascript">
$.jgrid.nav.addtext = "Add User";
$.jgrid.nav.edittext = "Edit User";
$.jgrid.nav.deltext = "Delete User";
</script>

After adding captions, the alignment got it out, so put this css.

<style type="text/css">
.ui-jqgrid .ui-jqgrid-pager .ui-pg-div
{
    float: left;
    line-height: 18px;
    padding: 2px 2px 2px 0;
    position: relative;
}
</style>

^ Top

Please do these changes to enable footer summary row.

Step1: Enable footer row in options

$grid["footerrow"] = true;
$g->set_options($grid);

// set onload js event
$e["js_on_load_complete"] = "grid_onload";
$grid->set_events($e);

Step2: Add custom JS code as mentioned. 'list1' is the identifier for grid. In function 'getCol', 2nd param 'field1' is the name of column, which will show the summary data. Valid options for mathoperation (4th param) are - 'sum, 'avg', 'count'.

<script>
function grid_onload()
{
    var grid = $("#list1"),
    sum = grid.jqGrid('getCol', 'field1', false, 'sum');
    grid.jqGrid('footerData','set', {field1: 'Total: '+sum});
}
</script>

If one need to show complete table's total in footer, refer following example.

$g->select_command = "SELECT id,invdate,total,(SELECT sum(total) from invheader) AS table_total FROM invheader";

Define a column with name table_total, and in footer data, use that table_total field.

<script>
function grid_onload()
{
    var grid = $("#list1");
    sum = grid.jqGrid('getCol', 'table_total');
    grid.jqGrid('footerData','set', {total: 'Total: '+sum[0]});
}
</script>

^ Top

Q) How to remove buttons and text from toolbar?

Do following config to show/remove items in toolbar

$opt["rowList"] = array();
$opt["pgbuttons"] = false;
$opt["pgtext"] = null;
$opt["viewrecords"] = false;
$g->set_options($opt);

$g->set_actions(array(
                        "add"=>false, // allow/disallow add
                        "edit"=>false, // allow/disallow edit
                        "delete"=>false, // allow/disallow delete
                        "view"=>false, // allow/disallow view
                        "refresh" => false, // show/hide refresh button
                        "search" => false, // show single/multi field search condition (e.g. simple or advance)
                    )
                );

^ Top

Q) How to caption header and both toolbars altogether?

Use this config:

In grid settings:

$opt["caption"] = "";
$opt["height"] = "100%";
$g->set_options($opt);

In html code:

<style>
.ui-jqgrid-pager,.ui-jqgrid-toppager
{ display: none; }
</style>

^ Top

Q) How to do grouping on more than 1 field?

It's not fully stable, but you can try following config.

$grid["grouping"] = true;
$grid["groupingView"] = array();

$grid["groupingView"]["groupField"] = array("field1","field2"); // specify column name to group listing
$grid["groupingView"]["groupDataSorted"] = array(true,true); // show sorted data within group
$grid["groupingView"]["groupSummary"] = array(true,true); // work with summaryType, summaryTpl, see column: $col["name"] = "total";

$grid["groupingView"]["groupColumnShow"] = array(false,false); // either show grouped column in list or not (default: true)
$grid["groupingView"]["groupText"] = array("<b>{0} - {1} Item(s)</b>"); // {0} is grouped value, {1} is count in group
$grid["groupingView"]["groupOrder"] = array("asc"); // show group in asc or desc order
$grid["groupingView"]["groupCollapse"] = true; // Turn true to show group collapse (default: false)
$grid["groupingView"]["showSummaryOnHide"] = true; // show summary row even if group collapsed (hide)

Refer demos/appearence/grouping.php for more help.

^ Top

Q) How to do grouping collapse except first?

You can call click() of first group on load event of datagrid.

$opt["loadComplete"] = "function(){ $('.jqgroup:first span').click(); }";
// ...
$g->set_options($opt);

^ Top

Q) How to maintain vertical scroll position after grid reload?

First you need to get the handler for load complete.

$e["js_on_load_complete"] = "do_onload";
$g->set_events($e);

Then in callback, you can have following code.

<script>
function do_onload()
{
    if (jQuery(window).data('phpgrid_scroll'))
        jQuery('div.ui-jqgrid-bdiv').scrollTop(jQuery(window).data('phpgrid_scroll'));

    jQuery('div.ui-jqgrid-bdiv').scroll(function(){
        jQuery(window).data('phpgrid_scroll',jQuery('div.ui-jqgrid-bdiv').scrollTop());
    });
}
</script>

^ Top

Q) How to scroll to a particular row value after grid reload?

First you need to get the handler for load complete.

$e["js_on_load_complete"] = "do_onload";
$g->set_events($e);

Then in JS callback, you can have following code. This will iterate all rows and find row with name 'Victoria Ashworth'. It then uses row's first column 'client_id' to get id and focus it with scrollTop().

<script>
function do_onload()
{
    var rows =  $('#list1').getRowData();
    for (var i=0;i<rows.length;i++)
        if (rows[i].name == 'Victoria Ashworth')
        {
            var t = jQuery('tr.jqgrow[id='+rows[i].client_id+']').position().top;
            jQuery('div.ui-jqgrid-bdiv').scrollTop(t);
        }
}
</script>

^ Top

Q) How to highlight some cell based on row data ?

You can do it onload event of grid. First you need to connect event, and then write your desired logic in JS code.

In Grid config, set event callback.

$e["js_on_load_complete"] = "do_onload";
...
$grid->set_events($e);

In callback function, write your code.

function do_onload()
{
    var grid = $("#list1");
    var ids = grid.jqGrid('getDataIDs');
    for (var i=0;i<ids.length;i++)
    {
        var id=ids[i];
        if (grid.jqGrid('getCell',id,'qty') == '0')
        {
            grid.jqGrid('setCell',id,'price','','not-editable-cell'); // make cell uneditable
            grid.jqGrid('setCell',id,'price','',{'background-color':'lightgray'}); // make bgcolor to gray
        }
    }
}

^ Top

Q) How to apply formatting of rows, based on 2 or more fields.

You can use a load complete callback handler, and put conditional formatting JS code in it. For instance, refer following example, where list1 is grid id.

// PHP part
$e["js_on_load_complete"] = "do_onload";
...
$grid->set_events($e);

// HTML part
<script>
function do_onload(ids)
{
    if(ids.rows) jQuery.each(ids.rows,function(i){

        // format row when gender is 'male' and company name starts with 'Bl'
        if (this.gender.toLowerCase() == 'male' && this.company.indexOf('Bl') != -1)
        {
            jQuery('#list1 tr.jqgrow:eq('+i+')').css('background','inherit').css({'background-color':'#FBEC88', 'color':'green'});
        }
    });
}
</script>

^ Top

Q) How to show dropdown/select in buttons toolbar?

Following JS code, will display dropdown with toolbar buttons. It's upto your logic to show desired options and onchange function. Here 'list1' is assumed to be grid id.

<script>
    jQuery(window).load(function(){
        jQuery('#list1_pager_left').append ('<div style="padding-left: 5px; padding-top:2px; float:left"><select><option>None</option></select></div>');
    });
</script>

^ Top

Q) How to retain page number on page refresh?

You can have something like following, to preserve page number.

$grid = new jqgrid();

if (isset($_GET["jqgrid_page"]))
    $_SESSION["jqgrid_page"] = $_GET["jqgrid_page"];

$opt["caption"] = "Clients Data";
$opt["page"] = intval($_SESSION["jqgrid_page"]);
$grid->set_options($opt);

^ Top

Q) How to persist selection, data ordering, column order, page number, selection in grid, expand same subgrid on page refresh?

Include following JS plugins files in your page, and add 'opts' setting before 'echo $out' as mentioned below:

<!-- library for persistance storage -->
<script src="//cdn.jsdelivr.net/jstorage/0.1/jstorage.min.js" type="text/javascript"></script>
<script src="//cdn.jsdelivr.net/json2/0.1/json2.min.js" type="text/javascript"></script>
<script src="//cdn.rawgit.com/gridphp/jqGridState/63904a57244ef89fa58ca0fa146da8e2e6e4d395/jqGrid.state.js" type="text/javascript"></script>

<script>
var opts = {
    "stateOptions": {
                storageKey: "gridStateCookie",
                columns: true,
                filters: false,
                selection: true,
                expansion: true,
                pager: true,
                order: true
                }
    };
</script>

<div style="margin:10px">
<?php echo $out?>
</div>

^ Top

Q) How to keep page number persistence when back button is clicked from new page?

Here we need some JS trick to pick if back button is clicked. When defining URL in column, here we've placed #moved in url and used JS onclick to send to new page.

$col = array();
$col["title"] = "Note";
$col["name"] = "note";
$col["width"] = "50";
$col["editable"] = true; // this column is editable
$col["default"] = "<a href='#moved' onclick=\"location.href='details.php'\">Details</a>"; // render as select
$cols[] = $col;

Enable state persistence of paging, all rest disabled.

var opts_list1 = {
        "stateOptions": {
                    storageKey: "gridState-list1",
                    columns: false, // remember column chooser settings
                    selection: false, // row selection
                    expansion: false, // subgrid expansion
                    filters: false, // filters
                    pager: true, // page number
                    order: false // field ordering
        }
    };

And to open first page if not back is clicked, i will clear state persistance if not hash is found in url.

<body>
    <script>
    jQuery(document).ready(function(){
        if(window.location.hash=="")
        {
            jQuery.jStorage.deleteKey('gridState-list1');
        }
    });
    </script>

    ....

</body>

^ Top

Q) How to apply more advanced conditional formatting?

You can set onload event in PHP code, and enable 'reloadedit' option

// set js onload event
$e["js_on_load_complete"] = "grid_onload";
$g->set_events($e);

// required to format rows after editing
$opt["reloadedit"] = true;
...
$g->set_options($opt);

Then in HTML code, you can have custom conditional logic in javascript handler. In this code, list1 is grid id. You can also use php's equivalent '$g->id' to reference it.

<script>
function grid_onload(ids)
{
    if(ids.rows)
        jQuery.each(ids.rows,function(i)
        {
            // if col1 = yes and col2 = n/a, format row
            if (this.col1.toLowerCase() == 'yes' && this.col2.toLowerCase() == 'n/a')
            {
                // highlight row
                jQuery('#list1 tr.jqgrow:eq('+i+')').css('background-image','inherit').css({'background-color':'#FBEC88', 'color':'red'});
            }

            // if col3 = 1, format cell. 'aria-describedby=list1_col3' is 'gridid_colname' convention to identify cell.
            if (parseInt(this.col3) == 1)
            {
                // highlight cell
                jQuery('#list1 tr.jqgrow:eq('+i+')').css('background-image','inherit');
                jQuery('#list1 tr.jqgrow:eq('+i+') td[aria-describedby=list1_col3]').css('background','inherit').css({'background-color':'#FBEC88', 'color':'red'});
            }
        });
}
</script>

To make non-editable column as gray, e.g. If 'list1' is grid id and 'name' is non-editable column:

<script>
function grid_onload(ids)
{
    if(ids.rows)
        jQuery.each(ids.rows,function(i)
        {
            // if col3 = 1, format cell. 'aria-describedby=list1_col3' is 'gridid_colname' convention to identify cell.
            if (jQuery("#list1").getColProp("name").editable == false)
            {
                // highlight cell
                jQuery('#list1 tr.jqgrow:eq('+i+')').css('background-image','inherit');
                jQuery('#list1 tr.jqgrow:eq('+i+') td[aria-describedby=list1_name]').css('background','inherit').css({ 'color':'gray'});
            }
        });
}
</script>

^ Top

Q) How to make single row selection, keeping multiselect option?

Following code will enable single selection, in multiselect mode.

PHP code config:

$opt["beforeSelectRow"] = "function(rowid, e) { if ( jQuery('#list1').jqGrid('getGridParam','selarrrow') != rowid) jQuery('#list1').jqGrid('resetSelection'); return true; }";
$g->set_options($opt);

where list1 is grid id.

^ Top

Q) How to turn multiselect on / off dynamically?

Following code will enable toggle multiselect via javascript code.

<input type="button" value="Multiselect" onclick="toggle_multiselect()">

<script>
function toggle_multiselect()
{
    if ($('#list1 .cbox:visible').length > 0)
    {
        $("#list1").jqGrid('setGridParam',{multiboxonly : true});
        $('#list1').jqGrid('hideCol', 'cb');
    }
    else
    {
        $("#list1").jqGrid('setGridParam',{multiboxonly : false});
        $('#list1').jqGrid('showCol', 'cb');
    }
}
</script>

where list1 is grid id.

^ Top

Q) How to make select row only by checkbox?

Following code will enable row selection by checkbox.

$opt["multiselect"] = true;
$opt["beforeSelectRow"] = "function(rowid, e) { return $(e.target).is('input[type=checkbox]'); }";
$g->set_options($opt);

^ Top

Q) How to increase font size of grid?

Following css override will adjust fonts. For any other left area, you can inspect using firebug.

<style>
.ui-jqgrid {
    font-family: "tahoma","verdana","sans serif";
    font-size: 12px;
}

.ui-jqgrid .ui-pg-table td {
    font-size: 12px;
}
</style>

^ Top

Q) How to stop reload grid after edit submit button?

Following config will stop whole grid reload, and will only update edited row.

$grid["edit_options"]["reloadAfterSubmit"]=false;
...
$g->set_options($grid);

^ Top

Q) How to attach Keyboard Shortcuts with operations like Add, Search etc?

You can bind your shortcut keys by adding following lib:

<script src="//cdn.jsdelivr.net/jquery.hotkeys/0.8b/jquery.hotkeys.js"></script>

More help on keys are available on its site: http://github.com/tzuryby/hotkeys

Next, you will find the ID of button to attach shortcut. Use firebug inspect to hover that button and it would show ID of the element.

e.g. To add 'insert' key with '+' button in toolbar

<script>
// insert key to add new row
$(document).bind('keyup', 'insert', function(){
      jQuery('#add_list1').click();
    });
</script>

^ Top

Q) How to increase overall Grid & Toolbar font size?

Following on-page styles will increase font-size to 14px (overriding the base css). This inclues grid font, dialogs and toolbar. This will be helpful when using in mobile devices.

<style>
/* increase font & row height */
.ui-jqgrid *, .ui-widget, .ui-widget input, .ui-widget select, .ui-widget textarea, .ui-widget button { font-size:14px; }
.ui-jqgrid tr.jqgrow td { height:30px; }

/* big toolbar icons */
.ui-pager-control .ui-icon, .ui-custom-icon { zoom: 125%; -moz-transform: scale(1.25); -webkit-zoom: 1.25; -ms-zoom: 1.25; }
.ui-jqgrid .ui-jqgrid-pager .ui-pg-div span.ui-icon { margin: 0px 2px; }
.ui-jqgrid .ui-jqgrid-pager { height: 28px; }
.ui-jqgrid .ui-jqgrid-pager .ui-pg-div { line-height: 25px; }
</style>

^ Top

Q) How to show animated progress bar instead of text 'Loading...'?

You can replace text with some string containing html tag.

$grid["loadtext"] = "Loading...";
$g->set_options($grid);

Q) How to show animated progress bar when submit data / form?

You can do it using BlockUI plugin: http://stackoverflow.com/a/22927642/385377

Refer integration demo here: Line 46,55 https://gist.github.com/gridphp/915d2e0834354913fdfd338d47d50a53

^ Top

Q) How to make button for next record selection in grid ?

Following code will bind JS code with button. where list1 is grid id.

<input type="button" value="Next" id="btnNext">

<script>
$('#btnNext').click(function () {

    var grid =  $("#list1").jqGrid();

    var selectedRow = grid.getGridParam('selrow');
    if (selectedRow == null) return;

    var ids = grid.getDataIDs();
    var index = grid.getInd(selectedRow);

    if (ids.length < 2) return;

    index++;
    if (index > ids.length)
        index = 1;

    grid.setSelection(ids[index - 1], true);
});
</script>

^ Top

Q) How to focus on next tabindex of HTML element onEnter keypress?

Following JS code will enable this onEnter next tabindex movement. Place it at end on html code.

<script type="text/javascript">
// Focus Next on Enter
// https://stackoverflow.com/a/40686327/8743891

function focusNextElement() {
  var focussableElements = 'a:not([disabled]), button:not([disabled]), input[type=text]:not([disabled]), [tabindex]:not([disabled]):not([tabindex="-1"])';
    var focussable = Array.prototype.filter.call(document.querySelectorAll(focussableElements),
      function(element) {
        return element.offsetWidth > 0 || element.offsetHeight > 0 || element === document.activeElement
      });
    var index = focussable.indexOf(document.activeElement);
    focussable[index + 1].focus();
}
window.addEventListener('keydown', function(e) {
  if (e.keyIdentifier == 'U+000A' || e.keyIdentifier == 'Enter' || e.keyCode == 13) {
    if (e.target.nodeName === 'INPUT' && e.target.type !== 'textarea') {
        e.preventDefault();
        focusNextElement();
        e.stopImmediatePropagation()
        return false;
    }
  }
}, true);
</script>

^ Top