Basic Grid


Conventions

An instance of jqGrid is a java script object, with properties, events and methods. Properties may be strings, numbers, arrays, boolean values or even other objects.

Calling Convention:

Java Script code

...
$("#grid_id").jqGrid(options);
...

HTML

<!DOCTYPE html>
<head>
...
</head>
<body>
...
  <table id="grid_id"></table>
...        
</body>
</html>

Where:

  • grid_id is the id of the table element defined separately in your html and used as the name of your grid.
  • options is an object of settings in "name: value" pair format. Some of these settings are values, some are functions to be performed on their associated events. Some of these settings are optional while others are mandatory for jqGrid to work

On creation of a grid you normally will set all relevant options directly, but it is possible also, to modify them later on: see Options

Events raised by the grid, which offer opportunities to perform additional actions, are described in Events.

The grid also offers several methods for getting or setting properties or data: see Methods

A key property of the grid is the column model (colModel) that defines the contents of the grid: colModel Options

Additional properties, events and methods of the basic grid, not described in this section, are used to create and manage the special types of grids: multiselect grids, subGrids, treeGrids, pivotGrid and more. Please refer to these topics for more details.

CSS Framework Guide

As of version 5 Guriddo jqGrid changes the way the styling of the grid is made. This mean that we have parametrize with classes every component of the grid. This allow us with little additions to make grid adoptable to any CSS framework.

Currently we have definitions for jQuery UI CSS Framework and Bootstrap CSS Framework

Below we will describe the construction of the styling and the way it works.

For using Guriddo jqGrid qith jQuery UI CSS and Bootstrap CSS see installation

CSS definition

Guriddo jqGrid stores the definition of the classes in the common $.jgrid object in the base module. The property which holds all the classes definitions is named styleUI. This property can be considered as main object describing the classes.

The next property in the hierarchy is the name which we give when defining the classes definitions. Currently we have two definitions - Bootstrap and jQueryUI. By example if we want to have Foundation CSS definition we can do this like this:

$.extend($.jgrid,{
...
styleUI : {
  jQueryUI : {
    ...
  },
  Bootstrap : {
    ...
  },
  Foundation : {
    ...
  }
},
...
});

This name should be used in case we want to use this CSS framework for a particular grid

...
  $("#grid").jqGrid({
   ...
   styleUI : 'Foundation'
  ...
  });

We name this property CSS Framework Definition Name (FDN)

Every CSS FDN has properties which describes the classes in certain Guriddo jqGrid modules. Gurrido jqGrid module is a file which holds the definitions, methods events and etc for a certain property of the grid. By example grid.base.js is the base module, while grid.treegrid.js holds the actions and definition for the treegrid. We have following CSS FDN properties:

  • common here we store the common classes which are available everywhere in the grid
  • base here we have a classes which are used in the jqGrid base module
  • modal describes the classes in the modal windows
  • celledit classes for cell editing module
  • inlinedit classes for inline editing module
  • formedit classes for form editing module
  • navigator classes for the navigator
  • grouping classes used in grouping
  • filter classes used in filter functions
  • subgrid classes in subgrid module
  • treegrid classes used in treegrid module
  • fmatter classes used in formatter
  • collmenu classes used in column menu

Bellow are the classes definitions for jQueryUI. The class properties are the same for Bootstrap. Note that if a new CSS definition will be made the same class properties should be used instead that some of them does not contain any definition.

styleUI : {
  jQueryUI : {
    common : {
      disabled: "ui-state-disabled",
      highlight : "ui-state-highlight",
      hover : "ui-state-hover",
      cornerall: "ui-corner-all",
      cornertop: "ui-corner-top",
      cornerbottom : "ui-corner-bottom",
      hidden : "ui-helper-hidden",
      icon_base : "ui-icon",
      overlay : "ui-widget-overlay",
      active : "ui-state-active",
      error : "ui-state-error",
      button : "ui-state-default ui-corner-all",
      content : "ui-widget-content"
    },
    base : {
      entrieBox : "ui-widget ui-widget-content ui-corner-all", // entrie div  incl everthing
      viewBox : "", // view diw
      headerTable : "",
      headerBox : "ui-state-default",
      rowTable : "",
      rowBox : "ui-widget-content",
      stripedTable : "ui-jqgrid-table-striped",
      footerTable : "",
      footerBox : "ui-widget-content",
      headerDiv : "ui-state-default",
      gridtitleBox : "ui-widget-header ui-corner-top ui-helper-clearfix",
      customtoolbarBox : "ui-state-default",
      //overlayBox: "ui-widget-overlay",
      loadingBox : "ui-state-default ui-state-active",
      rownumBox :  "ui-state-default",
      scrollBox : "ui-widget-content",
      multiBox : "",
      pagerBox : "ui-state-default ui-corner-bottom",
      pagerTable : "",
      toppagerBox : "ui-state-default",
      pgInput : "ui-corner-all",
      pgSelectBox : "ui-widget-content ui-corner-all",
      pgButtonBox : "ui-corner-all",
      icon_first : "ui-icon-seek-first",
      icon_prev : "ui-icon-seek-prev",
      icon_next: "ui-icon-seek-next",
      icon_end: "ui-icon-seek-end",
      icon_asc : "ui-icon-triangle-1-n",
      icon_desc : "ui-icon-triangle-1-s",
      icon_caption_open : "ui-icon-circle-triangle-n",
      icon_caption_close : "ui-icon-circle-triangle-s"
    },
    modal : {
      modal : "ui-widget ui-widget-content ui-corner-all ui-dialog",
      header : "ui-widget-header ui-corner-all ui-helper-clearfix",
      content :"ui-widget-content",
      resizable : "ui-resizable-handle ui-resizable-se",
      icon_close : "ui-icon-closethick",
      icon_resizable : "ui-icon-gripsmall-diagonal-se"
    },
    celledit : {
      inputClass : "ui-widget-content ui-corner-all"
    },
    inlinedit : {
      inputClass : "ui-widget-content ui-corner-all",
      icon_edit_nav : "ui-icon-pencil",
      icon_add_nav : "ui-icon-plus",
      icon_save_nav : "ui-icon-disk",
      icon_cancel_nav : "ui-icon-cancel"
    },
    formedit : {
      inputClass : "ui-widget-content ui-corner-all",
      icon_prev : "ui-icon-triangle-1-w",
      icon_next : "ui-icon-triangle-1-e",
      icon_save : "ui-icon-disk",
      icon_close : "ui-icon-close",
      icon_del : "ui-icon-scissors",
      icon_cancel : "ui-icon-cancel"
    },
    navigator : {
      icon_edit_nav : "ui-icon-pencil",
      icon_add_nav : "ui-icon-plus",
      icon_del_nav : "ui-icon-trash",
      icon_search_nav : "ui-icon-search",
      icon_refresh_nav : "ui-icon-refresh",
      icon_view_nav : "ui-icon-document",
      icon_newbutton_nav : "ui-icon-newwin"
    },
    grouping : {
      icon_plus : 'ui-icon-circlesmall-plus',
      icon_minus : 'ui-icon-circlesmall-minus'
    },
    filter : {
      table_widget : 'ui-widget ui-widget-content',
      srSelect : 'ui-widget-content ui-corner-all',
      srInput : 'ui-widget-content ui-corner-all',
      menu_widget : 'ui-widget ui-widget-content ui-corner-all',
      icon_search : 'ui-icon-search',
      icon_reset : 'ui-icon-arrowreturnthick-1-w',
      icon_query :'ui-icon-comment'
    },
    subgrid : {
      icon_plus : 'ui-icon-plus',
      icon_minus : 'ui-icon-minus',
      icon_open : 'ui-icon-carat-1-sw'
    },
    treegrid : {
      icon_plus : 'ui-icon-triangle-1-',
      icon_minus : 'ui-icon-triangle-1-s',
      icon_leaf : 'ui-icon-radio-off'
    },
    fmatter : {
      icon_edit : "ui-icon-pencil",
      icon_add : "ui-icon-plus",
      icon_save : "ui-icon-disk",
      icon_cancel : "ui-icon-cancel",
      icon_del : "ui-icon-trash"
    },
    colmenu : {
      menu_widget : 'ui-widget ui-widget-content ui-corner-all',
      input_checkbox : "ui-widget ui-widget-content",
      filter_select: "ui-widget-content ui-corner-all",
      filter_input : "ui-widget-content ui-corner-all",
      icon_menu : "ui-icon-comment",
      icon_sort_asc : "ui-icon-arrow-1-n",
      icon_sort_desc : "ui-icon-arrow-1-s",
      icon_columns : "ui-icon-extlink",
      icon_filter : "ui-icon-calculator",
      icon_group : "ui-icon-grip-solid-horizontal",
      icon_freeze : "ui-icon-grip-solid-vertical",
      icon_move: "ui-icon-arrow-4"
    }
  },
  ...
}

CSS rules

  1. We can set unlimited number of classes for class item separeted with space
  2. Class Item can contain empty string.
  3. The definition of the icon is a combination of the icon_base defined in common property plus the class of the icon.
  4. Every icon begin with 'icon'_ plus short description of the icon

Getting CSS classes

To get the classes for jQueryUI you can;

...
var jQueryUICSS = $.jgrid.styleUI.jQueryUI;
console.log(jQueryUICSS);
...

after the jqGrid JavaScript file is loaded. To get the common icon_base class:

...
var jQueryUICSS = $.jgrid.styleUI.jQueryUI;
console.log(jQueryUICSS.common.icon_base);
...

Setting CSS classes.

To set a particular item class it is a simple. Let suppose that we want to change the icon move in colmenu for jQueryUI style.

...
$.jgrid.styleUI.jQueryUI.colmenu.icon_move = 'ui-icon-arrow-1';
...

Of course if we want to change not only one CSS item from a group, but two or more we can use jQuery extend to do this

var my_col_definition  = {
  icon_move : 'ui-icon-arrow-1',
  icon_menu : "ui-icon-pencil"
}
$.extend( $.jgrid.styleUI.jQueryUI.colmenu , my_col_definition );

Language Guide

Guriddo jqGrid JS comes with a large number of predefined language packs and settings for almost all popular languages. They are located in the installation package, in the /js/trirand/i18n folder. Language packs are in the form of javascript files, containing definitions for all strings in the grid that can be localized - this includes messages, captions, paging information, search/add/delete dialog labels, etc.

The name of language file has the following structure:

grid.locale-XX.js

where XX is ISO 639-1 code which identifies the language.

The language javascript files can be loaded before or after jqGrid library. Historically the language file should be loaded before the jqGrid library, so we will continue with this.

Guriddo jqGrid can support different languages on one page. This means that you can load two or more language files and use it for a particular grid.

Another feature is that the language set of Guriddo jqGrid can be loaded dynamically without to reload the page - this is in case when appropriate language files are loaded.

Guriddo jqGrid can't work properly if the language file is not loaded. Be a sure that this file is loaded when working with the grid and setup correctly.

Below we will demonstrate two examples. The first example will load two grids in the page where each grid will be loaded with different language and the second example will change the language of the grid dynamically.

The appropriate settings and methods for this purpose are the grid option regional and the grid method setRegional

The regional option is a two letter string which corresponds to the ISO 639-1 code and the last two letter in grid language file definition.

The default value of this option is en.

It is important to note that using language file does not change the grid headers captions.
In order to change the caption grid cells use the grid method setLabel See Grid Methods

Using two grids on page with different language.

Let suppose that we need to use two grids in one page, where the one grid should use English texts, while the other should use Japanese. To resolve this situation we need to load these two language files and set on each grid the appropriate two letter code.

The javascript fragment can look like this:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Multi Lingual Grids</title>
<link rel="stylesheet" type="text/css" media="screen" href="css/jquery-ui.css" />
<link rel="stylesheet" type="text/css" media="screen" href="css/trirand/ui.jqgrid.css" />

<script src="js/jquery.min.js" type="text/javascript"></script>
<script src="js/trirand/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="js/trirand/i18n/grid.locale-jp.js" type="text/javascript"></script>
<script src="js/trirand/jquery.jqGrid.min.js" type="text/javascript"></script>
</head>
<body>

<table id='griden'></table>
<table id='gridjp'></table>

<script>
       var Array = [
         {name: 'Bob', phone: '232-532-6268'},
         {name: 'Jeff', phone: '365-267-8325'}
       ];

       $("#griden").jqGrid({
         datatype: 'local',
         regional: 'en', // this is default
         data: dataArray,
         colModel: [
            {name: 'name', label : 'Name'},
            {name: 'phone', label : 'Phone Number'}
          ]
      });
      $("#gridjp").jqGrid({
        datatype: 'local',
        regional: 'jp',
        data: dataArray,
        colModel: [
           {name: 'name', label : '名'},
           {name: 'phone', label : '電話番号'}
         ]
     });
</script>
</body>
</html>


Change language dynamically.

Changing language dynamically is possible with the common jqGrid function setReginal. To call it use the following code:

$.jgrid.setReginal('grid_id', {regional : 'bg'});

Let suppose that there is a requirement to change the language of the grid from English to Japanese when a button is a clicked. Using the header section from our previous example the code can look like this:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Multi Lingual Grids</title>
<link rel="stylesheet" type="text/css" media="screen" href="css/jquery-ui.css" />
<link rel="stylesheet" type="text/css" media="screen" href="css/trirand/ui.jqgrid.css" />

<script src="js/jquery.min.js" type="text/javascript"></script>
<script src="js/trirand/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="js/trirand/i18n/grid.locale-jp.js" type="text/javascript"></script>
<script src="js/trirand/jquery.jqGrid.min.js" type="text/javascript"><parametrize
<body>

<table id='grid'></table>
<button id='chnlng'>Change To Japones</button>

<script>
       var dataArray = [
         {name: 'Bob', phone: '232-532-6268'},
         {name: 'Jeff', phone: '365-267-8325'}
       ];

       $("#grid").jqGrid({
         datatype: 'local',
         regional: 'en', // this is default
         data: dataArray,
         colModel: [
            {name: 'name', label : 'Name'},
            {name: 'phone', label : 'Phone Number'}
          ]
      });
      $("#chnlng").on('click', function(){
        // change the language
        $.jgrid.setRegional('grid',{regional: 'jp'});
        // change the labels
        $("#grid").jqGrid('setLabel','name','名');
        $("#grid").jqGrid('setLabel','phone','電話番号');
      });

</script>
</body>
</html>

The first parameter in setRegional is the id of the grid and the second is a object containing property regional which should corresponded to the appropriate language file.

Language file structure.

The structure and properties of the language files are changed recently. To the time of writing this documentation the default English language file has the following structure and texts.

(function( factory ) {
    "use strict";
    if ( typeof define === "function" && define.amd ) {
        // AMD. Register as an anonymous module.
        define([
            "jquery",
            "../grid.base"
        ], factory );
    } else {
        // Browser globals
        factory( jQuery );
    }
}(function( $ ) {

$.jgrid = $.jgrid || {};
if(!$.jgrid.hasOwnProperty("regional")) {
    $.jgrid.regional = [];
}
$.jgrid.regional["en"] = {
    defaults : {
        recordtext: "View {0} - {1} of {2}",
        emptyrecords: "No records to view",
        loadtext: "Loading...",
        savetext: "Saving...",
        pgtext : "Page {0} of {1}",
        pgfirst : "First Page",
        pglast : "Last Page",
        pgnext : "Next Page",
        pgprev : "Previous Page",
        pgrecs : "Records per Page",
        showhide: "Toggle Expand Collapse Grid",
        // mobile
        pagerCaption : "Grid::Page Settings",
        pageText : "Page:",
        recordPage : "Records per Page",
        nomorerecs : "No more records...",
        scrollPullup: "Pull up to load more...",
        scrollPulldown : "Pull down to refresh...",
        scrollRefresh : "Release to refresh..."
    },
    search : {
        caption: "Search...",
        Find: "Find",
        Reset: "Reset",
        odata: [{ oper:'eq', text:'equal'},{ oper:'ne', text:'not equal'},{ oper:'lt', text:'less'},{ oper:'le', text:'less or equal'},{ oper:'gt', text:'greater'},{ oper:'ge', text:'greater or equal'},{ oper:'bw', text:'begins with'},{ oper:'bn', text:'does not begin with'},{ oper:'in', text:'is in'},{ oper:'ni', text:'is not in'},{ oper:'ew', text:'ends with'},{ oper:'en', text:'does not end with'},{ oper:'cn', text:'contains'},{ oper:'nc', text:'does not contain'},{ oper:'nu', text:'is null'},{ oper:'nn', text:'is not null'}, {oper:'bt', text:'between'}],
        groupOps: [{ op: "AND", text: "all" },{ op: "OR",  text: "any" }],
        operandTitle : "Click to select search operation.",
        resetTitle : "Reset Search Value",
        addsubgrup : "Add subgroup",
        addrule : "Add rule",
        delgroup : "Delete group",
        delrule : "Delete rule"
    },
    edit : {
        addCaption: "Add Record",
        editCaption: "Edit Record",
        bSubmit: "Submit",
        bCancel: "Cancel",
        bClose: "Close",
        saveData: "Data has been changed! Save changes?",
        bYes : "Yes",
        bNo : "No",
        bExit : "Cancel",
        msg: {
            required:"Field is required",
            number:"Please, enter valid number",
            minValue:"value must be greater than or equal to ",
            maxValue:"value must be less than or equal to",
            email: "is not a valid e-mail",
            integer: "Please, enter valid integer value",
            date: "Please, enter valid date value",
            url: "is not a valid URL. Prefix required ('http://' or 'https://')",
            nodefined : " is not defined!",
            novalue : " return value is required!",
            customarray : "Custom function should return array!",
            customfcheck : "Custom function should be present in case of custom checking!"

        }
    },
    view : {
        caption: "View Record",
        bClose: "Close"
    },
    del : {
        caption: "Delete",
        msg: "Delete selected record(s)?",
        bSubmit: "Delete",
        bCancel: "Cancel"
    },
    nav : {
        edittext: "",
        edittitle: "Edit selected row",
        addtext:"",
        addtitle: "Add new row",
        deltext: "",
        deltitle: "Delete selected row",
        searchtext: "",
        searchtitle: "Find records",
        refreshtext: "",
        refreshtitle: "Reload Grid",
        alertcap: "Warning",
        alerttext: "Please, select row",
        viewtext: "",
        viewtitle: "View selected row",
        savetext: "",
        savetitle: "Save row",
        canceltext: "",
        canceltitle : "Cancel row editing",
        selectcaption : "Actions..."
    },
    col : {
        caption: "Select columns",
        bSubmit: "Ok",
        bCancel: "Cancel"
    },
    errors : {
        errcap : "Error",
        nourl : "No url is set",
        norecords: "No records to process",
        model : "Length of colNames <> colModel!"
    },
    formatter : {
        integer : {thousandsSeparator: ",", defaultValue: '0'},
        number : {decimalSeparator:".", thousandsSeparator: ",", decimalPlaces: 2, defaultValue: '0.00'},
        currency : {decimalSeparator:".", thousandsSeparator: ",", decimalPlaces: 2, prefix: "", suffix:"", defaultValue: '0.00'},
        date : {
            dayNames:   [
                "Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat",
                "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
            ],
            monthNames: [
                "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
                "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
            ],
            AmPm : ["am","pm","AM","PM"],
            S: function (j) {return j < 11 || j > 13 ? ['st', 'nd', 'rd', 'th'][Math.min((j - 1) % 10, 3)] : 'th';},
            srcformat: 'Y-m-d',
            newformat: 'n/j/Y',
            parseRe : /[#%\\\/:_;.,\t\s-]/,
            masks : {
                // see http://php.net/manual/en/function.date.php for PHP format used in jqGrid
                // and see http://docs.jquery.com/UI/Datepicker/formatDate
                // and https://github.com/jquery/globalize#dates for alternative formats used frequently
                // one can find on https://github.com/jquery/globalize/tree/master/lib/cultures many
                // information about date, time, numbers and currency formats used in different countries
                // one should just convert the information in PHP format
                ISO8601Long:"Y-m-d H:i:s",
                ISO8601Short:"Y-m-d",
                // short date:
                //    n - Numeric representation of a month, without leading zeros
                //    j - Day of the month without leading zeros
                //    Y - A full numeric representation of a year, 4 digits
                // example: 3/1/2012 which means 1 March 2012
                ShortDate: "n/j/Y", // in jQuery UI Datepicker: "M/d/yyyy"
                // long date:
                //    l - A full textual representation of the day of the week
                //    F - A full textual representation of a month
                //    d - Day of the month, 2 digits with leading zeros
                //    Y - A full numeric representation of a year, 4 digits
                LongDate: "l, F d, Y", // in jQuery UI Datepicker: "dddd, MMMM dd, yyyy"
                // long date with long time:
                //    l - A full textual representation of the day of the week
                //    F - A full textual representation of a month
                //    d - Day of the month, 2 digits with leading zeros
                //    Y - A full numeric representation of a year, 4 digits
                //    g - 12-hour format of an hour without leading zeros
                //    i - Minutes with leading zeros
                //    s - Seconds, with leading zeros
                //    A - Uppercase Ante meridiem and Post meridiem (AM or PM)
                FullDateTime: "l, F d, Y g:i:s A", // in jQuery UI Datepicker: "dddd, MMMM dd, yyyy h:mm:ss tt"
                // month day:
                //    F - A full textual representation of a month
                //    d - Day of the month, 2 digits with leading zeros
                MonthDay: "F d", // in jQuery UI Datepicker: "MMMM dd"
                // short time (without seconds)
                //    g - 12-hour format of an hour without leading zeros
                //    i - Minutes with leading zeros
                //    A - Uppercase Ante meridiem and Post meridiem (AM or PM)
                ShortTime: "g:i A", // in jQuery UI Datepicker: "h:mm tt"
                // long time (with seconds)
                //    g - 12-hour format of an hour without leading zeros
                //    i - Minutes with leading zeros
                //    s - Seconds, with leading zeros
                //    A - Uppercase Ante meridiem and Post meridiem (AM or PM)
                LongTime: "g:i:s A", // in jQuery UI Datepicker: "h:mm:ss tt"
                SortableDateTime: "Y-m-d\\TH:i:s",
                UniversalSortableDateTime: "Y-m-d H:i:sO",
                // month with year
                //    Y - A full numeric representation of a year, 4 digits
                //    F - A full textual representation of a month
                YearMonth: "F, Y" // in jQuery UI Datepicker: "MMMM, yyyy"
            },
            reformatAfterEdit : false,
            userLocalTime : false
        },
        baseLinkUrl: *,
        showAction: *,
        target: *,
        checkbox : {disabled:true},
        idName : 'id'
    },
    colmenu : {
        sortasc : "Sort Ascending",
        sortdesc : "Sort Descending",
        columns : "Columns",
        filter : "Filter",
        grouping : "Group By",
        ungrouping : "Ungroup",
        searchTitle : "Get items with value that:",
        freeze : "Freeze",
        unfreeze : "Unfreeze",
        reorder : "Move to reorder"
    }
};
}));

Options

The setup and configuration of Guriddo jqGrid are controlled by setting options for the grid. Examples of configuration settings include the height and width of the grid, type of data that should be in each column, and other similar settings.

These options are set in the grid options object, and many of the options are set in name: value pairs, separated by commas. The object is given as an argument to the declaration of the jqGrid object.

The properties and options available are listed below in alphabetic order. Some have more details described in other pages of this documentation and a link to those pages is provided in those circumstances.

Some properties cannot be changed after the grid is created; the last column of the table labeled Can be changed? mentions if that particular property can or cannot have effect when changed after the grid is created.

All the grid options can be obtained with the method getGridParam, where the first parameter (string) is the name of the option. By example to get the selected row in grid with id 'grid' we can use:

...
var selected = $("#grid").jqGrid('getGridParam','selrow');
if(selected != null) {
  ...
} else {
  ...
}

We can set any option in a grid with the method setGridParam. The first parameter of this method is a object in name:value pair which contain the option(s) that we want to change. Note that if the value in column can not be changed (see below) is 'No', the new value will not have efect instead that it is changed in the grid options. To add additional parameter myparam = 20 to the data posted to the server do:

...
$("#grid").jqGrid('setGridParam',{ postData: { myparam:20 } });
...

Guriddo jqGrid has a its global object with name jQuery.jgrid or in short $.jgrid. This object contain variables and functions which are used everywhere in the grid. See Common functions and variables for a list of all available variables and functions.

The property $.jgrid.defaults can be used to set common options which are different from the default. See Setting Options Globaly.

When the grid is initialized it loads default text values from language file. These values are stored in $.grid.regional[XX].defaults property, where XX is a two code language letter. Below are the English values of this property:

$.jgrid.regional["en"] = {
    defaults : {
        recordtext: "View {0} - {1} of {2}",
        emptyrecords: "No records to view",
        loadtext: "Loading...",
        savetext: "Saving...",
        pgtext : "Page {0} of {1}",
        pgfirst : "First Page",
        pglast : "Last Page",
        pgnext : "Next Page",
        pgprev : "Previous Page",
        pgrecs : "Records per Page",
        showhide: "Toggle Expand Collapse Grid"
    },
...
}

These and all the grid options value are described below:

Property Type Description Default Can be Changed?
addOptions object The parameter stores the add options (parameters) in navigator see navigator if the option storeNavOptions is set to true and navGrid method is called empty No
ajaxCellOptions object When defined this option can overwrite the ajax options when cell editing is enabled and the cell submitting is defined via url. All the ajax options for cell submit can be overwriten. See Cell editing empty object Yes
ajaxGridOptions object This option allows to set global ajax settings for the grid when requesting data. With this option it is possible to overwrite all current ajax settings in the grid including the error, success and beforeSend events. empty object Yes
ajaxRowOptions object This option allow to set global ajax settings for the Inline editiing when we save the data to the server. Note that with this option is possible to overwrite all current ajax setting in the save request including the complete event. empty Yes
ajaxSelectOptions object This option allows to set global ajax settings for the created select element (in all editing and search modules) when the select is obtained via dataUrl option in editoptions or searchoptions objects See editing and searching empty object Yes
ajaxSubgridOptions object When defined this option can overwrite the ajax options in subgrid when the subgrid make a ajax call to obtain the data. See Subgrid empty Yes
altclass string This options is deprecated as of version 5.2
altRows boolean Set a zebra-striped grid (alternate rows have different styles). When this option is set to true we add a class described in styleUI object. The name of the class is stripedTable in the common styleUI object false No
autoencode boolean When set to true encodes the incoming data from server or array and encodes the posted data (from editing modules). For example < will be converted to &lt;. See the common functions for htmlEncode false Yes
autowidth boolean When set to true, the grid width is recalculated automatically to the width of the parent element. This is done only initially when the grid is created. In order to re-size the grid when the parent element or window changes width please use the option responsive - see below false No
caption string Defines the caption for the grid. This caption appears in the caption layer, which is above the header layer see How It Works. If the string is empty the caption does not appear. To change the caption dynamically use the method setCaption empty string No
cellLayout integer This option determines the padding + border width of the cell. Usually this should not be changed, but if custom changes to the td element are made in the grid css file, this will need to be changed. The initial value of 5 means paddingLef(2) + paddingRight (2) + borderLeft (1) = 5 5 No
cellEdit boolean Enables (disables) cell editing. See Cell Editing for more details. false Yes
cellsubmit string Determines where the contents of the cell should be saved. Possible values are remote in this case the data is saved via ajax and clientArray in case the data is saved in the local data array. See Cell Editing for more details. remote Yes
cellurl string The url where the cell is to be saved using ajax. Valid only if celsubmit is set to remote. See Cell Editing for more details null Yes
cmTemplate object Defines a set of properties which override the default values in colModel for all columns. For example if you want to make all columns not sort-able, then only one property here can be specified instead of specifying it in all columns in colModel {sortable:false} null No
colFilters object If set the object defines the initial search rules for a field defined in colModel. The option is valid if colMenu option is set to true. For more information see Column menu. empty No
colMenu boolean Enables column menu for a column with a set of predefined actions. The menu creates a button on the header of each or certain grid cell which when clicked activate a form with a actions.For more information see Column menu. false No
colModel array Array which describes the parameters of the columns. This is the most important part of the grid. For a full description of all valid values see colModel API. empty array No
colNames array An array in which we place the names of the columns. This is the text that appears in the head of the grid (header layer). The names are separated with commas. Note that the number of elements in this array should be equal of the number elements in the colModel array. This option will be deprecated. To set the text in header use the label property in colModel empty No
data array An array that stores the local data passed to the grid. You can directly point to this variable in case you want to load an array data. See array data. It can replace the addRowData method which is slow on relative big data empty array Yes
datastr string The string of data when datatype parameter is set to xmlstring or jsonstring. null Yes
datatype string Defines in what format to expect the data that fills the grid. Valid options are xml (we expect data in xml format), xmlstring (we expect xml data as string), json (we expect data in JSON format), jsonstring (we expect JSON data as a string), local or clientSide (we expect data defined at client side (array data) a data option can be used), script (we expect data as javascript), function (custom defined function for retrieving data), JSONP (we expect a data from a remoute server ). See Retrieving Data. It is important to note that if this option is a function you should define how to retrieve a data - i.e grid expect from this function to fill the grid (you can use by example addJSONData) xml Yes
deepempty boolean This option should be set to true if an event or a plugin is attached to the table cell. The option uses jQuery empty for the row and all its children elements. This of course has speed overhead, but prevents memory leaks. This option should be set to true if a sortable rows and/or columns are activated. false Yes
delOptions object The parameter stores the delete options (parameters) in navigator see navigator if the option storeNavOptions is set to true and navGrid method is called empty No
deselectAfterSort boolean Applicable only when datatype : local is used. Deselects currently selected row(s) when a sort is applied. If set to false the selected rows remain instead of sorting. true Yes
direction string Determines the direction of text in the grid. The default is ltr (Left To Right). When set to rtl (Right To Left) the grid automatically changes the direction of the text. It is important to note that in one page we can have two (or more) grids where the one can have direction ltr while the other can have direction rtl. Not all browsers support fully rtl. If a problem is encountered, please notify Guriddo support ltr No
editOptions object The parameter stores the edit options (parameters) in navigator see navigator if the option storeNavOptions is set to true and navGrid method is called empty No
editurl string Defines the url for inline and form editing. May be set to clientArray to manually post data to server, see Editing. null Yes
emptyrecords string The string to display when the returned (or the current) number of records in the grid is zero. This option is valid only if viewrecords option is set to true. The default value depend from the language used in the current grid. Yes
ExpandColClick boolean When true, the tree grid is expanded and/or collapsed when we click anywhere on the text in the expanded column. In this case it is not necessary to click exactly on the expand/collapse icon. true No
ExpandColumn string Indicates which column (name property from colModel) should be used to expand the tree grid. If not set the first one is used. Valid only when the treeGrid option is set to true. null No
footerrow boolean If set to true this will place a footer table with one row below the gird records and above the pager. The number of columns equal those specified in colModel false No
forceFit boolean If set to true, and a column's width is changed, the adjacent column (to the right) will resize so that the overall grid width is maintained (e.g., reducing the width of column 2 by 30px will increase the size of column 3 by 30px). In this case there is no horizontal scroll bar. Note: This option is not compatible with shrinkToFit option - i.e if shrinkToFit is set to false, forceFit is ignored. false No
frozenColumns boolean Read-only parameter. If this parameter is true it means that the frozen columns method is applied to the grid. false No
gridstate string Determines the current state of the grid (i.e. when used with hiddengrid, hidegrid and caption options). Can have either of two states: visible or hidden. This is only readonly option. visible No
gridview boolean In the previous versions of jqGrid (<= 3.4.X), reading a relatively large data set (number of rows >= 100 ) caused speed problems. The reason for this was that as every cell was inserted into the grid we applied about 5 to 6 jQuery calls to it. Now this problem is resolved; we now insert the entry row at once with a jQuery append. The result is impressive - about 3 to 5 times faster. What will be the result if we insert all the data at once? Yes, this can be done with a help of gridview option. The result is a grid that is 5 to 10 times faster compared to versions <= 3.4.X. This option have some limitations - we can not use aterInsertRow event. To use this event set the gridview option to false. true Yes
groupHeader object Read-only parameter which contain information about Header grouping empty No
grouping boolean Enables grouping in grid. Please refer to the Grouping. false Yes
groupingView object Holds the definitions for grouping See Grouping. Yes
headertitles boolean If the option is set to true the title attribute with text from the label property of colModel is added to the column headers - i.e if pointed with the mouse on the column header the header text display as title. false No
height mixed The height of the grid. Can be set as number ( pixels) or as percentage (only 100% is acceped) or value of auto is acceptable. In the last two cases (100% or auto) the vertical scrollbar does not appear. To change the height dynamically use the method setGridHeight 150 No.
hiddengrid boolean If set to true the grid is initially is hidden. The data is not loaded (no request is sent) and only the caption layer is shown. When the show/hide button is clicked for the first time to show grid, the request is sent to the server, the data is loaded, and grid is shown. From this point we have a regular grid. This option has effect only if the caption property is not empty and the hidegrid property (see below) is set to true. false No
hidegrid boolean Enables or disables the show/hide grid button, which appears on the right side of the caption layer. Takes effect only if the caption property is not an empty string. true No
hoverrows boolean When set to false the effect of mouse hovering over the grid data rows is disabled. true Yes
idPrefix string When set, this string is added as prefix to the id of every grid row when it is built. This option is usefull if a two or more grids are available and there is a possibility to have equal id and equal grid names. empty Yes
ignoreCase boolean By default the local searching is case-sensitive. To make the local search and sorting not case-insensitive set this options to true false Yes
inlineData empty object object used to add additional content (again with the edited row) to the data posted to the server when we are in inline editing. See Inline editing. This is a user defined object when there is a need to post additional data to the server. {} Yes
inlineNav boolean Read-only parameter - determines if the inline navigator (inlineNav method) is called for this grid instance - true or not - false false No
jsonReader array An object which describes the structure of the expected json data. For a full description and default setting, see Retrieving Data JSON Data No
keyName string Contain the name which is supposed to be used as index (unique id in grid row) when read the data and build the grid rows. The name is get from the key property in colModel. If the key property is not set this option is false. false No
lastpage integer Gives the total number of pages returned from the request. If you use a function as datatype, jqGrid('setGridParam',{lastpage: your_number}); can be used to specify the max pages in the pager. 0 No
lastsort integer Read-only property. Gives the index of last sorted column beginning from 0. 0 No
loadonce boolean If this flag is set to true, the grid loads the data from the server only once (using the appropriate datatype). After the first request, the datatype parameter is automatically changed to local and all further manipulations are done on the client side. The data parameter is filled with the response data from the server. false No
loadtext string The text which appears in progress indicator (when enabled) when requesting and sorting data. This parameter is located in language file. See the default property of the regional array. No
loadui string This option controls what to do when an ajax operation is in progress.
disable - disables the jqGrid progress indicator. This way you can use your own indicator.
enable (default) - shows the text set in the loadtext property in the center of the grid.
block - displays the text set in the loadtext property and blocks all actions in the grid until the ajax request completes. Note that this disables paging, sorting and all actions on toolbar, if any.
The method progressBar controll this behaviour.
enable Yes
mtype string Defines the type of ajax request to make ('POST' or 'GET') GET
minColWidth integer Defines the minimal width of the column when re-sizing. 33 Yes
multiboxonly boolean This option works only when the multiselect option is set to true (see below). When multiselect is set to true, clicking anywhere on a row selects that row; when multiboxonly is also set to true, the multiselection is done only when the checkbox is clicked. Clicking in any other row (suppose the checkbox is not clicked) deselects all rows and selects the current row. See Multiselection false Yes
multikey string This parameter makes sense only when the multiselect option (see below) is set to true. Defines the key which should be pressed when we make multiselection. The possible values are: shiftKey - the user should press Shift Key, altKey - the user should press Alt Key, and ctrlKey - the user should press Ctrl Key. See Multiselection empty Yes
multimail boolean If this options is set to true and the multiselect is on, the selection is like Yahoo and Google mail. Multiselection is done so that the multiboxonly parameter is set to true with additional properties. See Multiselection false Yes
multiselect boolean If this flag is set to true a multi selection of rows is enabled. A new column at left side containing checkboxes is added. Can be used with any datatype option. See options selarrrow which contain the selected rows. See Multiselection false No
multiselectWidth integer Determines the width of the checkbox column created when the multiselect option is enabled. 30 No
multiSort boolean If set to true enables the multisorting - sort on more than one field. The options work if the datatype is local too. In case when the data is obtained from the server the sidx parameter contain the order clause. It is a comma separated string in format field1 asc, field2 desc ..., fieldN. Note that the last field does not have asc or desc. It should be obtained from sord parameter. When the option is true the behavior is as follow. The first click of the header field sort the field depending on the firstsortoption parameter in colModel or sortorder grid parameter. The next click sort it in reverse order. The third click removes the sorting from this field. false Yes
navButtons array The parameter stores all the custom buttons created in navigator see navigator if the option storeNavOptions is set to true and navButtonAdd method is called empty No
navGrid boolean Readonly parameter. determines if the navGrid method is called for this grid instance - true or not - false false No
navOptions object The parameter stores the navigator options in navigator if the option storeNavOptions is set to true and navGrid method is called empty No
page integer Set the initial page number when we make the request.This parameter is passed to the url for use by the server routine retrieving the data. It also works when the datatype is local. 1 Yes
pager html id Defines the pager bar to navigate through the records. This must be a valid HTML element; in our example we gave the div the id of "pager", but any name is acceptable. Note that the navigation layer (the "pager" div) can be positioned anywhere you want, determined by your HTML; in our example we specified that the pager will appear after the body layer. The valid settings can be (in the context of our example) pager, #pager, jQuery('#pager'). We recommend to use the second one - #pager. See Pager for more details and explanations. If the pager is empty string (default value) it will not appear. ' ' No
pagerpos string Determines the position of the pager navigation buttons and records select box in the grid. By default the pager element when created is divided in 3 parts (one part for pager navigator buttons, one part for navigator buttons and one part for record information - see recordpos). Possible values are left, center, right. Note that when changing the position of this parameter it is necessary to change the position of the other elements. See Navigator options and the parameter recordpos below. center No
pgbuttons boolean Determines if the Pager buttons should be shown if pager is available. Also valid only if pager is set correctly. The buttons are placed in the pager bar. true No
pginput boolean Determines if the input box, where the user can change the number of the requested page, should be available. The input box appears in the pager bar between the pager buttons. true No
pgtext string Show information about current page status. We use for this purpose a template string. The default English string is: Page {0} of {1}. The first value '{0}' is the current loaded page. The second value '{1}' is the total number of pages. Default depend from the used language file lang file Yes
prmNames array The default value of this property is:
{page:"page",rows:"rows", sort:"sidx", order:"sord", search:"_search", nd:"nd", id:"id", oper:"oper", editoper:"edit", addoper:"add", deloper:"del", subgridid:"id", npage:null, totalrows:"totalrows"}.
This customizes names of the fields sent to the server on a POST/GET request. All of the values correspond to some options of the grid. For example, with this setting, you can change the sort order element from sidx to mysort by setting prmNames: {sort: "mysort"}. The string that will be posted to the server will then be myurl.php?page=1&rows=10&mysort=myindex&sord=asc, rather than myurl.php?page=1&rows=10&sidx=myindex&sord=asc. So the value of the column on which to sort upon can be obtained by looking at $POST['mysort'] in PHP by example. When some parameter is set to null, it will be not sent to the server. For example if we set prmNames: {nd:null} the nd parameter will not be sent to the server. For npage option see the scroll option. These options have the following meaning and default values:
page: the requested page (default value page),
rows: the number of rows requested (default value rows),
sort: the sorting column (default value sidx),
order: the sort order (default value sord),
search: the search indicator (default value _search),
nd: the time passed to the request (for IE browsers not to cache the request) (default value nd),
id: the name of the id when posting data in editing modules (default value id),
oper: the operation parameter passed to the server (default value oper),
editoper: the name of operation when the data is posted in edit mode (default value edit),
addoper: the name of operation when the data is posted in add mode (default value add),
deloper: the name of operation when the data is posted in delete mode (default value del),
totalrows: the number of the total rows to be obtained from server - see rowTotal (default value totalrows),
subgridid: the name passed when we click to load data in the subgrid (default value id).
Yes
postData object This array is appended directly to the url. This is an object and can be used this way: {name1:value1...}. This is a user defined object which extends the object passed to the data parameter in ajax request. See API methods for manipulation. empty Yes
reccount integer Read-only property. Determines the exact number of rows in the grid. Do not confuse this with records parameter. Although in many cases they may be equal, there are cases where they are not. For example, if you define rowNum (requested records per page) to be 15, but the request to the server returns 20 records, the records parameter will be 20, but the reccount parameter will be 15 (the grid you will have 15 records and not 20). 0 No
recordpos string Determines the position of the record information in the pager ( See recordtext option). Can be left, center, right. If the default value is changed, be a sure that the other placement in 3 part pager are set in appropriate way. right No
records integer Readonly property. Gives the number of records returned as a result of a query to the server. none No
recordtext string Text that can be shown in the pager. This option is valid if viewrecords option is set to true. This text appears only if the total number of records is greater then zero. The default string in case of english langauage is as following: View {0} - {1} of {2}. {0} is the start position of the records depending on page number and number of requested records, {1} is the end position and {2} - total records returned from the server. lang file Yes
regional string Two letter code which correspond to the code in grid.locale-xx.js. To load a language file different from English (default) in the grid change this parameter with the appropriate code. Note that the language file should be loaded. See setRegional method and Language Guide. en Yes
remapColumns array Array which contain the order of the columns as they apper in the grid. Initially the first position correspond to the first column and etc. - by example [0,1,2,3] in case we have 4 columns defined in colModel. After reordering of columns ( see Column reorder ) the array can look like this: [1,0,3,2]. This mean the the first column(0) is moved to the second position(1) and the third column(2) is moved to four position(3). Using the method remapColumns we can dynamically remap the initial order of the columns in the grid. After this remapping the array remapColumns is set to the those in the method. empty Yes
resizeclass string Assigns a class to columns that are re-sizable so that we can show a re-size handle only for ones that are resizable. empty No
responsive boolean If set to true the grid is re sized automatically to its parent container when the device is rotated or when the windows width is changed. Another useful feature is auto calculating the the space of the navGrid buttons – if the space does not fit the grid width drop down menu button is created, where all actions are inserted. false No
restoreCellonFail boolean Determine if the cell should be set or restored to its initial state on fail. Use this option if validation module is performed. The option is valid only in cell editing module. For More information see Cell editing. true Yes
rowList array An array to construct a select box element in the pager in which we can change the number of the visible rows. When changed during the execution, the values of this parameter replaces the rowNum parameter that is passed to the url. If the array is empty, this element does not appear in the pager. Typically you can set this like [10,20,30]. If the rowNum parameter is set to 30 then the selected value in the select box is 30. The rowList parameter can have display value as string too. The select list can be configured with a name value pair where the value and display text will be separated with colon ":". By example the following ["10:10", "20:20", "30:30", "-1:All"] will provide display items in select list 10,20,30,All and when All is selected the value of -1 will be posted. empty No
rownumbers boolean If this option is set to true, a new column at left of the grid is added. The purpose of this column is to count the number of available rows, beginning from 1. In this case colModel is extended automatically with new element with the name rn. Note: It is not recommend to use the name rn in the colModel. false No
rowNum integer Sets how many records we want to view in the grid. This parameter is passed to the url (and in local data too) for use by the server routine retrieving the data. Note that if you set this parameter to 10 (i.e. retrieve 10 records) and your server return 15 then only 10 records will be loaded. 20 Yes
rowTotal integer When set this parameter can instruct the server to load the total number of rows needed to work on. Note that rowNum determines the total records displayed in the grid, while rowTotal determines the total number of rows on which we can operate. When this parameter is set, we send an additional parameter to the server named totalrows (See prmNames option). You can check for this parameter, and if it is available you can replace the rows parameter with this one. Mostly this parameter can be combined with loadonce parameter set to true. null Yes
rownumWidth integer Determines the width of the row number column if rownumbers option is set to true. 35 No
savedRow array This is a readonly property and is used in inline and cell editing modules to store the data, before editing the row or cell. See Cell Editing and Inline Editing. This array stores the original values before editing the cell or row and is used in case the user press Esc to restore the original values of the edited row or cell. empty No
search boolean Read-only parameter which identify if we perform a search. The parameter is set to true if we use one of the search modules and activate the search (server side or local). The parameter is set to false when the search is reset. false No
searchOptions object The parameter stores the search options (parameters) in navigator see navigator if the option storeNavOptions is set to true and navGrid method is called empty No
scroll mixed Creates dynamic (virtual) scrolling grids. When enabled, the pager buttons and select box are disabled and we can use the vertical scrollbar to load data. When set to true the grid will always hold all the items from the start through to the latest point ever visited. When scroll is set to an integer value (Mostly by example 1), the grid will just hold the visible lines. This allow us to load the data in portions without caring about memory leaks. In addition to this we have an optional extension to the server protocol: npage (see prmNames array). If you set the npage option in prmNames, then the grid will sometimes request more than one page at a time; if not, it will just perform multiple GET requests.Note that this option is not compatible when a grid parameter height if set to auto or 100%. false No
scrollMaxBuffer integer This parameter set the maximum rows the grid can load when a scroll option is set to 1. This allow to control the buffer of the loaded rows. This parameter is recommended to be used when a scroll is set to 1 and the datatype is local. The recommended setting is a value greater than the rowNum parameter. If the value is little then this parameter it is set automatically to be equal to rowNum parameter. 0 Yes
scrollLeftOffset percent Determines the left offset of the box which appear when virtual scroll is enabled and scrollPopUp parameter is set to true. The information does appear when we use the mouse to scroll through the pages. The value of 0% set the box to appear at upper left corner of the grid. See scrollPopUp and scrollTopOffset parameters. 100% Yes
scrollOffset integer Determines the width of the vertical scrollbar. Since different browsers interpret this width differently (and it is difficult to calculate it in all browsers) this can be changed. 18 No
scrollTopOffset integer Defines the top offset from the upper position of the scroll element. 0 Yes
scrollPopUp boolean Enables/disables popup with page information when virtual scrolling is on. When this is enabled the information box change its position relative to the position of the scroll element. false Yes
scrollTimeout integer This controls the timeout handler when scroll is set to 1. The value is set in milliseconds. 40 Yes
scrollrows boolean When enabled, selecting a row with setSelection scrolls the grid so that the selected row is visible. This is especially useful when we have a verticall scrolling grid and we use form editing with navigation buttons (next or previous row). On navigating to a hidden row, the grid scrolls so that the selected row becomes visible. false Yes
selarrrow array This options is readonly. Gives the currently selected rows when multiselect is set to true. This is a one-dimensional array and the values in the array correspond to the selected id's in the grid. empty No
selrow string This option is read-only. It contains the id of the last selected row. If sorting or paging is performed, this options is set to null. null No
shrinkToFit boolean This option, if set, defines how the the width of the columns of the grid should be re-calculated, taking into consideration the width of the grid. If this value is true, and the width of the columns is also set, then every column is scaled in proportion to its width. For example, if we define two columns with widths 80 and 120 pixels, but want the grid to have a width of 300 pixels, then the columns will stretch to fit the entire grid, and the extra width assigned to them will depend on the width of the columns themselves and the extra width available. The re-calculation is done as follows: the first column gets the width (300(new width)/200(sum of all widths))80(first column width) = 120 pixels, and the second column gets the width (300(new width)/200(sum of all widths))120(second column width) = 180 pixels. Now the widths of the columns sum up to 300 pixels, which is the width of the grid. If the value is false and the value in width option is set, then no re-sizing happens whatsoever. So in this example, if shrinkToFit is set to false, column one will have a width of 80 pixels, column two will have a width of 120 pixels and the grid will retain the width of 300 pixels. true No
sortable mixed When set to true, this option allows reordering columns by dragging and dropping them with the mouse. Since this option uses the jQuery UI sortable widget, be sure to load this widget and its related files in the HTML head tag of the page. Note: The colModel object also has a property called sortable, which specifies if the grid data can be sorted on a particular column or not. This option works when Bootstrap CSS is used. In this case the jQuery UI sortable widged should be loaded. The sortable option can be a object in which we can add (or overwrite) parameters that are available in the jQuery UI method. To do this a option property should be set. By example to change the jQuery UI sortable pareneter forcePlaceholderSize we should do:
$("#jqGrid").jqGrid({ ..., sortable: { options: {forcePlaceholderSize : true } },...});.
Actually when this option is on we call the build in method sortabColumns
false No
sortname string The column according to which the data is to be sorted when it is initially loaded from the server or local array. This parameter is appended to the url. If this value is set and the index (name) matches the name from colModel, then an icon indicating that the grid is sorted according to this column is added to the column header. This icon also indicates the sorting order - descending or ascending (see the parameter sortorder). Also see prmNames. empty Yes
sortorder string The initial sorting order (ascending or descending) when we fetch data from the server or client array. This parameter is appended to the url - see prnNames. The two allowed values are - asc or desc. asc Yes
storeNavOptions boolean Store the navigator options in the grid options. The parameter is used in navGrid method (common navigator options) and if true the options are saved as grid parameters. This parameter is usefull if we want to know some parameter in the navigator, but the primary use of this parameter is when a loadState and restoreState methods are used. In this case it is recommend to set this option to true since restoring of navigator actions depend from grid option. false No
styleUI string Defines the CSS framework used for the internal representation of the grid. For more information refer to CSS Framework Guide. jQueryUI No
subGrid boolean If set to true this enables using a sub-grid. If the subGrid option is enabled, an additional column at left side is added to the basic grid. This column contains expanded/collapsed icon (see subgrid property in StyleUI) which indicates that the user can click on it to expand the row. By default all rows are collapsed. See Subgrid for details false No
subGridOptions object A set of additional options for the subgrid. For more information and default values see Subgrid. Yes
subGridModel array This property, which describes the model of the subgrid, has an effect only if the subGrid property is set to true. It is an array in which we describe the column model for the subgrid data. For more information see Subgrid. empty No
subgridtype mixed Set the dataType of the ajax call to the server when make the subgrid request. Can be xml or json. Can be a function. If not set, get the datatype defined in the grid option datatype. null Yes
subGridUrl string This option has effect only if the subGrid option is set to true. This option points to the url from which we get the data for the subgrid. jqGrid adds the id of the row to this url as parameter. If there is a need to pass additional parameters, use the params option in subGridModel. See Subgrid empty string Yes
subGridWidth integer Defines the width of the sub-grid column if subGrid is enabled. 20 No
toolbar array This option defines the toolbar of the grid. This is an array with two elements in which the first element's value enables the toolbar and the second defines the position relative to the body layer (table data). Possible values are top, bottom, and both. When we set it like toolbar: [true,"both"] two toolbar s are created -- one on the top of table data and the other at the bottom of the table data. When we have two toolbar s, then we create two elements (div). The id of the top bar is constructed by concatenating the string "t_" and the id of the grid, like "t_" + id_of_the_grid and the id of the bottom toolbar is constructed by concatenating the string "tb_" and the id of the grid, like "tb_" + id_of_the grid. In the case where only one toolbar is created, we have the id as "t_" + id_of_the_grid, independent of where this toolbar is located (top or bottom) [false,''] No
toppager boolean When enabled this option places a pager element at top of the grid, below the caption (if available). If another pager is defined, both can coexist and are kept in sync (except adding custom buttons in navigator). The id of the newly created pager is the combination grid_id + "_toppager". All the buttons which are connected to the 'bottom' pager are valid for the top pager. This means that if by example pginput is true it will display on the toppager too. false No
totaltime integer Readonly parameter. It gives the loading time of the records - currently available only when we load xml,json or jsonp data. The measurement begins when the request is complete and ends when the last row is added. 0 No
treedatatype mixed Gives the initial datatype when tree grid is enabled (see datatype option). Usually this should not be changed. During the reading process this option is equal to the datatype option. null No
treeGrid boolean Enables (disables) the tree grid format. For more details see Tree Grid false No
treeGridModel string Method used for the treeGrid. The value can be either nested or adjacency. See Tree Grid nested No
treeIcons array This array sets the icons used in the tree grid.The default values are set from styleUI property treegrid of the used CSS framework. No
treeReader object Extends the colModel defined in the basic grid when treeGrid is set to true. The fields described here are appended to end of the colModel array and are hidden. This means that the data returned from the server should have values for these fields. For a full description of all valid values see Tree Grid. No
tree_root_level numeric Defines the level from where the root element begins when treeGrid is enabled. 0 No
url string The url of the file that returns the data needed to populate the grid. May be set to clientArray to manually post data to server; see Editing. null Yes
userData object This object contains custom information from the request. Can be used at any time. See Retrieving Data. empty No
userDataOnFooter boolean When set to true we directly place the user data array userData in the footer if the footerrow parameter is set to true. The rules are as follows: If the userData array contains a name which matches any name defined in colModel, then the value is placed in that column. If there are no such values nothing is placed. Note that if this option is used we use the current formatter options (if available) for that column. See footerData method false Yes
viewOptions object The parameter stores the view options (parameters) in navigator see navigator if the option storeNavOptions is set to true and navGrid method is called empty No
viewrecords boolean If true, jqGrid displays the beginning and ending record number in the grid, out of the total number of records in the query. This information is shown in the pager bar (bottom right by default)in this format: "View X to Y out of Z". If this value is true, there are other parameters that can be adjusted, including emptyrecords and recordtext. false No
viewsortcols array The purpose of this parameter is to define a different look and behavior for the sorting icons (up/down arrows) that appear in the column headers. This parameter is an array with the following default options viewsortcols : [false,'vertical',true]. The first parameter determines if sorting icons should be visible on all the columns that have the sortable property set to true. Setting this value to true could be useful if you want to indicate to the user that (s)he can sort on that particular column. The default of false sets the icon to be visible only on the column on which that data has been last sorted. Setting this parameter to true causes all icons in all sortable columns to be visible. The second parameter determines how icons should be placed - vertical means that the sorting arrows are one under the other. 'horizontal' means that the arrows should be next to one another. The third parameter determines the click functionality. If set to true the data is sorted if the user clicks anywhere in the column's header, not only the icons. If set to false the data is sorted only when the sorting icons in the headers are clicked. Important: If you are setting the third element to false, make sure that you set the first element to true; if you don't, the icons will not be visible and the user will not know where to click to be able to sort, since clicking just anywhere in the header will not guarantee a sort. No
width number If this option is not set, the width of the grid is the sum of the widths of the columns defined in the colModel (in pixels). If this option is set, the initial width of each column is set according to the value of the shrinkToFit option. To change the grid width use setGridWidth method. none No
xmlReader object An object which describes the structure of the expected xml data. For a full description refer to Retrieving Data in XML Format. No

Setting Options globaly


There are cases where you want to have some particular options to be changed (change the default value) and that this option should be a common for all your grids. This can be done using extend function of jQuery.

Let us suppose that you want to have a zebra like grid (alternate rows have different colors) and want that all you grids have this options set to true. If you do not want this code to be written every time when you create a grid, here is a way to do it :

...
<script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>
<script type="text/javascript">
...
// Here we set the altRows option globally
jQuery.extend(jQuery.jgrid.defaults, { altRows:true });
...
</script>

This code should be placed after loading jqGrid JavaScript file.

You can add as many valid jqGrid options as you want here.

Overwrite options


In the previous example, we learn how to set common options for all grids in your application. However, you might encounter situations where you would like to overwrite the global and or default options for a particular grid.

To do this, you will need to change the option in the desired grid. For example, let's say we set a global option for all rows to have alternating colors (the zebra grid). If we don't want alternating colors for a certain grid, just set altRows to false and the global option will be overwritten.

The code for this scenario can be found here:

...
<script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>
<script type="text/javascript">
...
// Here we set the altRows option globally
jQuery.extend(jQuery.jgrid.defaults, { altRows:true });
...
</script>
...
<script type="text/javascript">
jQuery(document).ready(function(){
  jQuery("#list").jqGrid({
    url:'example.php',
    // here we do not want zebra for this grid
    altRows: false,
    ...
  });
  ...
});

colModel options


The colModel property defines the individual grid columns as an object of properties. This is the most important part of the jqGrid. Syntax of setting colModel is:

jQuery("#gridid").jqGrid({
...
   colModel: [
     {name:'name1', index:'index1'...},
     {...},
     ...
   ],
...
});

The minimal required property is name.

The colModel options can be get or set using getColProp and setColProp methods. See Methods.

To get a properties of column with name name1 do:

...
var myprop = jQuery("#gridid").jqGrid('getColProp', 'name1');
...

The method has only one parameter - column name. If the column name does not exists the method return empty object.

To set a property(s) of column with name with name1 do:

...
jQuery("#gridid").jqGrid('setColProp', 'name1', {index:'newindex',...});
...

In this case the index property of column with name name1 will be changed from index1 to newindex.
Parameters passed to the method are column name and a object of type name:value.

To get the entire colModel array use getGridParam method.

...
var colmodel = jQuery("#gridid").jqGrid('getGridParam', 'colModel');
...

The available colModel properties are listed here, in alphabetic order. Some propties contain other objects. These properties will be described in the appropriate chapter - link will be provided.

Property Type Description Default
align string Defines the alignment of the cell in the Body layer, not in header cell. Possible values: left, center, right. left
cellattr function This function add attributes to the cell during the creation of the data - i.e dynamically. By example all valid attributes for the table cell can be used or a style attribute with different properties. The function should return string. Parameters passed to this function are:
rowId - the id of the row
val - the value which will be added in the cell
rawObject - the raw object of the data row - i.e if datatype is json - array, if datatype is xml xml node.
cm - all the properties of this column listed in the colModel
rdata - the data row which will be inserted in the row. This parameter is array of type name:value, where name is the name in colModel
null
classes string This option allow to add classes to the column. If more than one class will be used a space should be set. By example classes:'class1 class2' will set a class1 and class2 to every cell on that column. In the grid css there is a predefined class ui-ellipsis which allow to attach ellipsis to a particular row. Also this will work in FireFox too. empty string
colmenu boolean Enables/disables column menu to appear at particular grid header. This option is valid only if the grid option colMenu is set to true. See Column menu true
coloptions object Defines a various options for colum menu if it is enabled.For more information see Column menu. empty
datefmt string Governs format of sorttype:date (when datetype becomes local) or/and editrules {date:true} fields. Determines the expected date format for that column - i.e the format set here should correspond to the value which will be inserted into the grid. Uses a PHP-like date formatting. Currently "/", "-", and "." are supported as date separators. Valid formats are:
y,Y,yyyy for four digits year
YY, yy for two digits year
m,mm for months
d,dd for days.
The values is used to sort the date correct and validate it in case of editing with validation (editrules) See Array Data
Y-m-d
editable boolean Defines if the field is editable. This option is used in cell-, inline- and form-editing modules. By default this option is false, which means that in inline and cell editing the field is not allowed to be edit. In form editing the field does not appear into the edit form. See Editing false
editoptions object Object of allowed options (properties) for the editable column. The option is valid if editable option is set to true. See Edit options empty
editrules object Object sets additional rules for the editable field. Mostly used for validation. See Edit rules empty
edittype string Defines the edit type for editing modules. Possible values: text, textarea, select, checkbox, password, button, image and file and etc. See also Edit type text
exportcol boolean Determines if the column should be exported when using exportToCsv, exportToExcel and exportToPdf methods. If set to false the column is not exported. See Exporting true
firstsortorder string Can be set to asc or desc, the column will be sorted in that direction on first sort. Subsequent sorts of the column will toggle as usual asc
fixed boolean If set to true this option does not allow recalculation of the width of the column if shrinkToFit option is set to true. Also the width does not change if a setGridWidth method is used to change the grid width. false
formoptions object Defines various options for form editing. See Form options empty
formatoptions object Format options can be defined for particular columns, overwriting the defaults from the language file. See Formatter for more details. none
formatter mixed Set predefined types (string) or custom function name that controls the format of this field. See Formatter for more details. none
frozen boolean If set to true determines that this column will be frozen after calling the setFrozenColumns method. See Frozen Columns false
hidedlg boolean If set to true this column will not appear in the dialog where users can choose which columns to show, hide or reorder using the columnChooser method jQuery UI Integrations or colMenu Column action. false
hidden boolean Defines if this column is hidden at initialization. The column is not editable and will not show in Form editing. Instead tha the column is hidden the data is presented in the grid. See methods hideCol and showCol. See editrules to edit a column in form edit when hidden. false
index string Set the index name when sorting. Passed as sidx parameter. If set this field is used in serching - i.e the field is send to the server for serching or used in local searching. empty
jsonmap mixed Defines the json mapping for the column in the incoming json request/string. Can be used as function with parameter the row data. See Retrieving JSON Data none
key boolean Overwrite the id (defined in readers) from server or array data. Can be set as id for the unique row id. Only one column can have this property. This option have higher priority as those from the readers. If there are more than one key set the grid finds the first one and the second is ignored. When set this option is equal to the grid option keyName. false
label string When colNames array is empty, defines the header caption for this column. If both the colNames array and this setting are empty, the heading for this column is values of name property. none
name string Set the unique name in the grid for the column. This property is required. As well as other words used as property/event names, the reserved words (which cannot be used for names) include subgrid, cb and rn. Required
resizable boolean Defines if the column can be re sized with the mouse or resizeColumn method. true
search boolean When used in search modules, disables or enables searching on that column. Search Configuration true
searchoptions object Defines search options used in searching. Search Configuration empty
sortable boolean Defines if the field can be sorted. If false click with the mouse on that column does not provide any action. true
sortfunc function Custom function to make custom sorting when datatype is local. Three parameters a, b and direction are passed. The a and b parameters are values to be compared, direction is numeric 1 and -1 for ascending and descending order. The function should return the same values as the build in JavaScript function sort - ie: 1, -1 or 0. null
sorttype mixed Used when datatype is local. Defines the type of the column for appropriate sorting and searching. Possible values:
int/integer - for sorting integer
float/number/currency - for sorting decimal numbers
date - for sorting date (see datefmt parameter)
text - for text sorting
function* - defines a custom function for sorting type. To this function we pass the value to be sorted and it should return a value.
See Array Data
text
stype string Determines the input type of the element when searching - the possible values are text for creating input field and select for select element. See Search Configuration text
surl string This option is deprecated. Use searchoptions : {dataUrl:'...'} instead. See Searching. empty
template object Set of valid properties for the colModel. This option can be used if you want to overwrite a lot of default values in the column model with easy. By example you can define a common object with valid colModel options and set it here to overwrite default one. See also cmTemplate in grid options null
title boolean If this option is false the title is not displayed in that column when we hover a cell with the mouse true
width number Set the initial width of the column, in pixels. This value accept only number and the measure is in pixels. 150
widthOrg number This width is equal to the initial set width and does not change during resizing of the grid. 150
xmlmap string Defines the xml mapping for the column in the incoming xml file. A CSS specification for this can be defined. Can be used as function with parameter the xmlrow data. See Retrieving Data none
unformat function Custom function to "unformat" a value (to bring it in its original state) of the cell when used in editing and user defined formatter is used. See Custom Formatter and Editing. (Unformat is also called during sort operations. The value returned by unformat is the value compared during the sort.) null
viewable boolean This option is valid only when viewGridRow method is activated. When the option is set to false the column does not appear in view Form. true


Data - retrieving, mapping, configuration


This is the most important part of Guriddo jqGrid. Understanding this will make the rest of using Guriddo jqGrid very easy.

Guriddo jqGrid support obtaining data from the following basic format types: JSON, XML and Array data, which can be considered as subpart of JSON.

The data is obtained via Ajax or/and locally with the appropriate JSON String, XML String and Array data.

The following items are related with the data:

Basic Guriddo jqGrid options

  • datatype
  • jsonReader
  • xmlReader
  • localReader
  • data
  • url
  • datastr
  • loadonce

Basic Guriddo jqGrid events

  • serializeGridData
  • beforeProcessing
  • loadComplete
  • gridComplete
  • loadError
  • loadBeforeSend

Basic Guriddo jqGrid functions

  • addJSONData
  • addXmlData
  • addLocalData

Basic colModel options

Here are options valid for every object (jqGrid column) described in colModel array.

  • xmlmap
  • jsonmap
  • key

Basic Guriddo jqGrid methods

  • addRowData
  • delRowData
  • setRowData
  • getRowData
  • setCell
  • getCell
  • getCol
  • getLocalRow

JSON Data


JSON is the most important exchange format today. Guriddo jqGrid maps the external JSON data from ajax (or other sources) to grid using the main parameter jsonReader.

Te default setting of jsonReader is:

jQuery("#gridid").jqGrid({
...
   jsonReader : {
      root: "rows",
      page: "page",
      total: "total",
      records: "records",
      repeatitems: true,
      cell: "cell",
      id: "id",
      userdata: "userdata",
      subgrid: {
         root:"rows",
         repeatitems: true,
         cell:"cell"
      }
   },
...
});

To allow this to happen the grid option datatype should be set to json, jsonp (in case of jsonstring datastr option should be set with the json string input data).

jQuery("#gridid").jqGrid({
...
  datatype: 'json',
  url : 'data.json'
...
});

Using our Quick Start example let suppose that we have the following grid.

$("#grid").jqGrid({
  datatype: 'json',
  url : 'data.json'
  colModel: [
     {name: 'name', label : 'Name'},
     {name: 'phone', label : 'Phone Number'}
   ]
});

In this case using the default jsonReader we can accept two JSON data formats. The first one should be:

{
  "total": "1",
  "page": "1",
  "records": "2",
  "rows" : [
    {"id" :"1", "cell" :["Bob", "232-532-6268"]},
    {"id" :"2", "cell": ["Jeff", "365-267-8325"]}
  ]
}

and the second one should be:

{
  "total": "1",
  "page": "1",
  "records": "2",
  "rows" : [
    {"id" :"1", "name": "Bob", "phone": "232-532-6268", "addres":"address 1"},
    {"id" :"2", "name": "Jeff", "phone": "365-267-8325", "addres":"address 2"}  
  ]
}

Note the differences in row property. This means that Guriddo jqGrid can auto detect the input JSON format to put the data into the grid.

Note: When using the input format as set in the first example the length of the cell array should be equal to the length of colModel. In case of difference no data will be present to the grid.

The properties used in jsonReader mean the following:

Property Description
total total pages for the query
page current page of the query
records total number of records for the query
rows an array that contains the actual data
id the unique id of the row
cell an array that contains the data for a row
repeatitems tells jqGrid that the information for the data in the row is repeatable - i.e. the elements have the same tag cell described in cell array element. Setting this option to false instructs jqGrid to search elements in the json data by name. This is the name from colModel or the name described with the jsonmap option in colModel
userdata holds additional data from serevr to be presented in grid. See userdata below
subgrid Definition for subgrid. See Subgrid

Let's begin our walk through the jsonReader.

The first element is a

  • root

This element describes where our row data begins. In other words, this points to the array that contains the data. If we set :

jQuery("#gridid").jqGrid({
  ...
  jsonReader : {root:"clientdata"},
  ...
});

then the returned string should be

{
  "total": "1",
  "page": "1",
  "records": "2",
  "clientdata" : [
    {"id" :"1", "cell" :["Bob", "232-532-6268"]},
    {"id" :"2", "cell": ["Jeff", "365-267-8325"]}
  ]
}

The

  • page
  • total
  • records

elements describe the information needed for the pager. For example, if the jsonReader is set as follows:

jQuery("#gridid").jqGrid({
...
   jsonReader : {
      root:"clientdata",
      page: "currpage",
      total: "totalpages",
      records: "totalrecords"
   },
...
});

then the data should be :

{
  "totalpages": "1",
  "currpage": "1",
  "totalrecords": "2",
  "clientdata" : [
    {"id" :"1", "cell" :["Bob", "232-532-6268"]},
    {"id" :"2", "cell": ["Jeff", "365-267-8325"]}
  ]
}

The

  • cell

element describes the array which contains the data for the row.

jQuery("#gridid").jqGrid({
...
   jsonReader : {
      root:"clientdata",
      page: "currpage",
      total: "totalpages",
      records: "totalrecords",
      cell: "clrow"
   },
...
});

The data to match this description would be

 {
   "totalpages": "1",
   "currpage": "1",
   "totalrecords": "2",
   "clientdata" : [
     {"id" :"1", "clrow" :["Bob", "232-532-6268"]},
     {"id" :"2", "clrow": ["Jeff", "365-267-8325"]}
   ]
 }

The
- id

element describes the unique id for the row. This id is set as id in the jqGrid table row element. It is very important to note that the id should be unique for every row.

jQuery("#gridid").jqGrid({
...
   jsonReader : {
      root:"clientdata",
      page: "currpage",
      total: "totalpages",
      records: "totalrecords",
      cell: "clrow",
      id : "clid"
   },
...
});

The data for this description is:

{
  "totalpages": "1",
  "currpage": "1",
  "totalrecords": "2",
  "clientdata" : [
    {"clid" :"1", "clrow" :["Bob", "232-532-6268"]},
    {"clid" :"2", "clrow": ["Jeff", "365-267-8325"]}
  ]
}

It is possible to set the cell element to an empty string. And, it is possible to set the id as number. Here is an example of these possibilities:

jQuery("#gridid").jqGrid({
...
   jsonReader : {
      root:"clientdata",
      page: "currpage",
      total: "totalpages",
      records: "totalrecords",
      cell: "",
      id : "0"
   },
...
});

In this case the id is the first element from the row data

{
  "totalpages": "1",
  "currpage": "1",
  "totalrecords": "2",
  "clientdata" : [
    ["1","Bob", "232-532-6268"],
    ["2", "Jeff", "365-267-8325"]
  ]
}

The

  • repeatitems

element tells Guriddo jqGrid that the information for the data in the row is repeatable - i.e. the elements have the same tag cell described in cell element. Setting this option to false instructs jqGrid to search elements in the json data by name. This is the name from colModel or the name described with the jsonmap option in colModel.

Here is an example:

jQuery("#gridid").jqGrid({
...
   jsonReader : {
      root:"clientdata",
      page: "currpage",
      total: "totalpages",
      records: "totalrecords",
      repeatitems: false,
      id : "0"
   },
...
});

The resulting data in our example should be:

{
  "totalpages": "1",
  "currpage": "1",
  "totalrecords": "2",
  "clientdata" : [
    {"clid" :"1", "name":"Bob", "phone": "232-532-6268"},
    {"clid" :"2", "name": "Jeff", "phone": "365-267-8325"}
  ]
}

The id element in this case is 'clid'. The same result will be if we set id to clid in the above example.

A very useful feature here (repeatitems:false) is that there is no need to include all the data that is represented in colModel. Since we make a search by name, the order does not need to match the order in colModel. Hence the following JSON data will be correctly interpreted in jqGrid.

{
  "totalpages": "1",
  "currpage": "1",
  "totalrecords": "2",
  "clientdata" : [
    {"clid" :"1", "phone": "232-532-6268"},
    {"clid" :"2", "name": "Jeff"}
  ]
}

JSON String

The jsonstring option has the same features as json. The only difference is that the data is passed as string. In this case we need to have a valid JSON data string. The string should be passed in datastr grid option.

JSON dot notation

When using JSON data with named values (i.e the repeatitems option is false) we can use named dot notation and index notation.

For example, our colModel definition might be as follows:

$("#grid").jqGrid({
  datatype: 'json',
  url : 'data.json'
  colModel: [
     {name: 'client.name', label : 'Name'},
     {name: 'client.phone', label : 'Phone Number'}
   ]
});

Note the elements defined as name:'client.name' and name:'client.phone'

Then our data:

{
  "total": "1",
  "page": "1",
  "records": "2",
  "rows" : [
    {"id" :"1", "client" : { "name": "Bob", "phone": "232-532-6268" }, "addres":"address 1"},
    {"id" :"2", "client" : { "name": "Jeff", "phone": "365-267-8325"}, "addres":"address 2"}  
  ]
}

jsonReader as Function

In certain situation data can be obtained from a web service. In this case it is not possible to configure all the properties of the response so that the grid will work properly. As of version 3.6.4 it is possible to define the elements of the jsonReader as function. Below is a example on how this can be used:

jsonReader: {
    repeatitems: false,
    id: "Id",
    root: function (obj) { return obj.rows; },
    page: function (obj) { return obj.page; },
    total: function (obj) { return obj.records; },
    records: function (obj) { return obj.rows.length; }
}

Where obj is the response from the service/server

Array Data

Despite the fact that the primary goal of jqGrid is to represent dynamic data returned from a database, jqGrid includes a wide range of methods to manipulate data at client side and we named it Array data.

See related items in Data related items

As of version 3.7 we introduce two additional parameters data and localReader. The data parameter is described in grid options. The localReader has the same sense as jsonReader described above, but applied to array data that is stored locally.

The initial configuration of the localReader is the same as those from jsonReader

localReader = {
   root: "rows",
   page: "page",
   total: "total",
   records: "records",
   repeatitems: false,
   cell: "cell",
   id: "id",
   userdata: "userdata",
   subgrid: {root:"rows", repeatitems: true, cell:"cell"}
}

All operations that are valid for jsonReader can be applied to localReader.

To use array data we should set the option datatype to local.

var dataArray = [
  {name: 'Bob', phone: '232-532-6268'},
  {name: 'Jeff', phone: '365-267-8325'}
];

$("#grid").jqGrid({
  datatype: 'local',
  data: dataArray,
  colModel: [
     {name: 'name', label : 'Name'},
     {name: 'phone', label : 'Phone Number'}
   ]
});

When using array data it is a good idea to set the sorttypes for the columns - this way the local sorting will be performed correct. If the sorttype is not set the default sorttype is 'text'. Let's consider our exyended example in terms of array data.

var dataArray = [
  {clid: 1, name: 'Bob', phone: '232-532-6268', birthday: "01/01/1971", salary: 1234.00},
  {clid: 2, name: 'Jeff', phone: '365-267-8325', birthday: "02/02/1972", salary 2345.00}
];

$("#grid").jqGrid({
  datatype: 'local',
  data: dataArray,
  colModel: [
    {name: 'clid', label : 'Id', sorttype: "int"},
    {name: 'name', label : 'Name'},
    {name: 'phone', label : 'Phone Number'},
    {name: 'birthday', label : 'Birth day', sorttype: 'date', datefmt:'d/m/Y'},
    {name: 'salary', label : 'Salary', sorttype: "float"},
  ]
});

In the example - additionally for the sorttype date we must known the format of the data that will be present in the grid. The default format is a ISO format 'Y-m-d'.

For local data manipulation see Data related items

XML Data

Extensible Markup Language (XML) is used to describe data. The XML standard is a flexible way to create information formats and electronically share structured data via the public Internet, as well as via corporate networks. More information what XML is can be found here

The rules of accessing the element from XML are the same as those used in jQuery library, i.e. CSS patterns. For more information refer here.

Guriddo jqGrid can read any attribute from the XML response. Moreover the tags can be set as function. See below.

The default setting for xmlReader is:

jQuery("#gridid").jqGrid({
...
   xmlReader : {
      root: "rows",
      row: "row",
      page: "rows>page",
      total: "rows>total",
      records : "rows>records",
      repeatitems: true,
      cell: "cell",
      id: "[id]",
      userdata: "userdata",
      subgrid: {
         root:"rows",
         row: "row",
         repeatitems: true,
         cell:"cell"
      }
   },
...
});

All the elements in the XML reader will be explained as examples rather than as strong description.

  • root element

The first setting here defines the root element. This describes where our data begins and all other loops begin from this element. For example,

<invoices>
   <request>true</request>
   ...
   <result>
      <row>
         <cell>data1</cell>
         <cell>data2</cell>
         <cell>data3</cell>
         <cell>data4</cell>
         <cell>data5</cell>
         <cell>data6</cell>
      </row>
      ...
   </result>
</invoices>

If we set the root element to result all data will be processed from there. In this case, because our rows are tagged and our cells tagged , all that is needed is to set.

jQuery("#gridid").jqGrid({
...
  xmlReader: { root:"result"},
...
});

The next element is the

  • row element.

This describes the information for particular row. Note that row must be a child of the root element. Here, if the XML looks like this:

...
<invoices>
   <request>true</request>
   ...
   <result>
      <invoice>
         <cell>data1</cell>
         <cell>data2</cell>
         <cell>data3</cell>
         <cell>data4</cell>
         <cell>data5</cell>
         <cell>data6</cell>
      </invoice>
      ...
   </result>
</invoices>

the setting to properly interpret this data would be

jQuery("#gridid").jqGrid({
...
   xmlReader: { root:"result", row:"invoice"  },
...
});

The

  • page
  • total and
  • records

elements describe the information needed for the pager. These elements can be, but do not have to be, a child of the root element. For example, to interpret this data,

...
<invoices>
  <request>true</request>
  ...
  <currentpage>1</currentpage>
  <totalpages>10</totalpages>
  <totalrecords>20</totalrecords>
  <result>
     <invoice>
        <cell>data1</cell>
        <cell>data2</cell>
        <cell>data3</cell>
        <cell>data4</cell>
        <cell>data5</cell>
        <cell>data6</cell>
     </invoice>
     ...
  </result>
</invoices>

the xmlReader will have to look like this:

jQuery("#gridid").jqGrid({
...
  xmlReader: {
     root:"result",
     row:"invoice",
     page:"invoices>currentpage",
     total:"invoices>totalpages",
     records:"invoices>totalrecords"
 },
...
});

The repeatitems and cell elements tells jqGrid that the information for the data in the row is repeatable - i.e. the elements have the same tag cell described in cell element. For this example,

...
<invoices>
   <request>true</request>
   ...
   <currentpage>1</currentpage>
   <totalpages>10</totalpages>
   <totalrecords>20</totalrecords>
   <result>
      <invoice>
         <invcell>data1</invcell>
         <invcell>data2</invcell>
         <invcell>data3</invcell>
         <invcell>data4</invcell>
         <invcell>data5</invcell>
         <invcell>data6</invcell>
      </invoice>
      ...
   </result>
</invoices>

the xmlReader will look like this:

jQuery("#gridid").jqGrid({
...
   xmlReader: {
      root:"result",
      row:"invoice",
      page:"invoices>currentpage",
      total:"invoices>totalpages",
      records:"invoices>totalrecords",
      repeatitems:true,
      cell:"invcell"
  },
...
});

Next is the

  • id

element. If repeatitems is set to true and key option in colModel is set to false the id, if present in XML data, must be a attribute of the row element. Lets look at the example:

...
<invoices>
  <request>true</request>
  ...
  <currentpage>1</currentpage>
  <totalpages>10</totalpages>
  <totalrecords>20</totalrecords>
  <result>
     <invoice asin='12345'>
        <invcell>data1</invcell>
        <invcell>data2</invcell>
        <invcell>data3</invcell>
        <invcell>data4</invcell>
        <invcell>data5</invcell>
        <invcell>data6</invcell>
     </invoice>
     ...
  </result>
</invoices>

In this case the xmlReader is:

jQuery("#gridid").jqGrid({
...
  xmlReader: {
     root:"result",
     row:"invoice",
     page:"invoices>currentpage",
     total:"invoices>totalpages",
     records:"invoices>totalrecords",
     repeatitems:true,
     cell:"invcell",
     id : "[asin]"
 },
...
});

Let's suppose that the structure of the XML document returned from the server has the following format:

...
<invoices>
  <request>true</request>
  ...
  <currentpage>1</currentpage>
  <totalpages>10</totalpages>
  <totalrecords>20</totalrecords>
  <result>
     <invoice>
        <asin>12345</asin>
        <invoiceno>data1</invoiceno>
        <invoicedate>data2</invoicedate>
        <invoiceamount>data3</invoiceamount>
        <invoicetax>data4</invoicetax>
        <invoicetotal>data5</invoicetotal>
        <notes>data6</notes>
     </invoice>
     ...
  </result>
</invoices>

where the <asin> tag describes the unique id and this should be set as the row id in the grid and not displayed in the grid. Following the rules we can construct the following:

jQuery("#gridid").jqGrid({
...
   xmlReader: {
      root:"result",
      row:"invoice",
      page:"invoices>currentpage",
      total:"invoices>totalpages",
      records:"invoices>totalrecords",
      repeatitems:false,
      id : "asin"
  },
...
});

and our colModel from the example should look like this (Note the xmlmap property):

<code javascript>
jQuery("#gridid").jqGrid({
...
   colModel :[
      {name:'invid', index:'invid', width:55, xmlmap:"invoiceno"},
      {name:'invdate', index:'invdate', width:90, xmlmap:"invoicedate"},
      {name:'amount', index:'amount', width:80, align:'right', xmlmap:"invoiceamount"},
      {name:'tax', index:'tax', width:80, align:'right', xmlmap:"invoicetax"},
      {name:'total', index:'total', width:80, align:'right', xmlmap:"invoicetotal"},
      {name:'note', index:'note', width:150, sortable:false, xmlmap:"notes"}
   ],
   xmlReader: {
      root:"result",
      row:"invoice",
      page:"invoices>currentpage",
      total:"invoices>totalpages",
      records:"invoices>totalrecords",
      repeatitems:false,
      id : "asin"
  },
...
});

The above data can be represented in colModel another way. If the names in colModel are not important for you, you can do the following.

jQuery("#gridid").jqGrid({
...
   colModel :[
      {name:'invoiceno', index:'invid', width:55},
      {name:'invoicedate', index:'invdate', width:90},
      {name:'invoiceamount', index:'amount', width:80, align:'right'},
      {name:'invoicetax', index:'tax', width:80, align:'right'},
      {name:'invoicetotal', index:'total', width:80, align:'right'},
      {name:'notes', index:'note', width:150, sortable:false}
   ],
   xmlReader: {
      root:"result",
      row:"invoice",
      page:"invoices>currentpage",
      total:"invoices>totalpages",
      records:"invoices>totalrecords",
      repeatitems:false,
      id : "asin"
  },
...
});

In other words, jqGrid first looks to see if there is an xmlmap option available; if this option is not available the name is used as the xmlmap. But all of this is true only if the repeatitems element in xmlReader is set to false.

The subgrid option is included in several of the xmlReader examples above. The principles in constructing the rules for this data are the same as those described above. More details about subgrids can be found in the section on Subgrids.

XML String

The xmlstring option has similar features to the XML option (See above). The only difference is that the data is passed as string. In this case is needed to have a valid XML data string. To do that a datastr option should be used.

If you use an XML string to obtain the data - after the data is retrieved the datatype option automatically is set to local.

The example from our tutorial can look like this.

<script>
var mystr =
"<?xml version='1.0' encoding='utf-8'?>
<invoices>
    <rows>
        <row>
          <clid>1</clid>
          <name>Bob</name>
          <phone>232-532-6268</phone>
          <birthday>01/01/1971</birthday>
          <salary>1234.00</salary>
        </row>
        <row>
          <clid>2</clid>
          <name>Jeff</name>
          <phone>232-532-6268</phone>
          <birthday>02/02/1972</birthday>
          <salary>2345.00</salary>
        </row>
    </rows>
</invoices>";

$("#grid").jqGrid({
  datatype: 'xmlstring',
  datastr: mystr,
  xmlReader : {
    repeatitems : false
  },
  colModel: [
    {name: 'clid', label : 'Id', sorttype: "int"},
    {name: 'name', label : 'Name'},
    {name: 'phone', label : 'Phone Number'},
    {name: 'birthday', label : 'Birth day', sorttype: 'data', datefmt:'d/m/Y'},
    {name: 'salary', label : 'Salary', sorttype: "float"},
  ]
});
...
</script>

As can be seen, this example introduces another option in colModel: sorttype. This option describes how a particular column is to be sorted, because when using xmlstring as the source for the grid, jqGrid uses client-side sorting.

Datatype as function

This option does not really define the datatype at all, but rather how to handle the data that is provided by the server (which would still come as either xml or json data). The functions defined as a Datatype should (or can) call addXMLData, addJSONData or addRowData once the data has been received. If you use a pager, it is useful to call your_grid.setGridParam({lastpage: your_number}) to specify the number of pages.

Calling Convention:

jQuery("#gridid").jqGrid({
...
  datatype : function(postdata) {
    // do something here
  }
...
});

Datatype functions are supplied with a object containing the request information (parameter postdata), which normally would have been transformed into GET or POST arguments. This object is compatible with the data option supplied to the jQuery $.ajax function.

Consider our example here is how this will work with datatype function:

<script type="text/javascript">
...
jQuery(document).ready(function(){
  jQuery("#list").jqGrid({
    datatype: function(postdata) {
        var thegrid = this;
        jQuery.ajax({
           url: 'example.php',
           data:postdata,
           dataType:"xml",
           complete: function(xmldata,stat){
              if(stat=="success") {
                 //var thegrid = jQuery("#list")[0];
                 thegrid.addXmlData(xmldata.responseXML);
              }
           }
        });
    },
    ...
  });
});
...
</script>

Userdata

In some cases we need to have custom data returned from the request that is not automatically displayed by jqGrid, that we use either in a later process or to display additional information somewhere in the HTML page or associated with the grid. To do that a userdata tag can be used.

In xmlReader this is defined as:

xmlReader: {
  ...
  userdata: "userdata",
  ...
}

This describes the tag where our custom data is. The important part here is that the XML tag should have a attribute name in order to associate data. In the data received from the server, this could be structured as follows:

<invoices>  
    <request>true</request>  
    <userdata name="totalinvoice"> 240.00 </userdata>  
    <userdata name="tax"> 40.00</userdata>
    ...
    <result>  
      <row>  
        <cell>data1</cell>
        <cell>data2</cell>
        <cell>data3</cell>
        <cell>data4</cell>
        <cell>data5</cell>
        <cell>data6</cell>
      </row>
      ...
    </result>
</invoices>

If using JSON data, the definition might look like this:

jsonReader: {
  ...
  userdata: "userdata",
  ...
}

and the data received, like this:

{
 total: "xxx",
 page: "yyy",
 records: "zzz",
 userdata: {totalinvoice:240.00, tax:40.00},
 rows : [
   {id:"1", cell:["cell11", "cell12", "cell13"]},
   {id:"2", cell:["cell21", "cell22", "cell23"]},
   ...
 ]
}

When this data has been received, this information is stored in the userData array of the options array. Whichever format the data comes in, in this case we would have:

userData = {totalinvoice:240.00, tax:40.00}

The data can be accessed using a getGridParam method. To do that we need to request this data:

jQuery("gridid").jqGrid('getGridParam', 'userData')

The userdata can be used as function. To this function we pass the response from the server. In case of JSON this is:

jsonReader: {
  ...
  userdata: function( jsondata ) {
    // do something here
  },
  ...
}

To get or set the userData on the footer row in the grid (if preset) a footerData method can be used. See Methods.

Events


The action to take on an event is set as a property of the grid, e.g.

var lastSel;
jQuery("#gridid").jqGrid({
...
   onSelectRow: function(id, orgEvent){
      if(id && id!==lastSel){
         jQuery('#gridid').jqGrid('restoreRow',lastSel);
         lastSel=id;
      }
      jQuery('#gridid').jqGrid('editRow',id, true);
   },
...
});

The above example specifies the action to take when a row is selected. The events that you can use to perform some additional action are listed here, in alphabetic order and are related only to the basic jqGrid. Other events related to editing subgrids and etc are described in the appropriate chapters.

To every event is passed the reference (this) to the grid. This means that inside every event you can use $(this) which refers to the current used grid. Using the above example both are equivalent.

var lastSel;
jQuery("#gridid").jqGrid({
...
   onSelectRow: function(id, orgEvent){
      if(id && id!==lastSel){
         jQuery(this).jqGrid('restoreRow',lastSel);
         lastSel=id;
      }
      jQuery(this).jqGrid('editRow',id, true);
   },
...
});

The event can be changed dynamically using the setGridParam method.

Triggered events

Alternatively jqGrid support the so named triggered events. These events are equivalent to the events defined in the grid properties. They are defined using jQuery .triggerHandler().

To define a such event use jQuery on. The code below is equvalent of the code above:

var lastSel;
jQuery("#gridid").on("jqGridSelectRow", function(event, id, orgEvent) {
  if(id && id!==lastSel){
    jQuery(this).jqGrid('restoreRow',lastSel);
    lastSel=id;
  }
  jQuery(this).jqGrid('editRow',id, true);
});

What are the diffrences between these two definitions.

  1. The trigered event is called outside jqGrid.
  2. When using triggered events we can register multiple event handlers - i.e bind different code to the same event depending a condition.
  3. The first parameter of the triggered event is a event and then follow the order of parameter(s) as defined in the "options" jqgrid events
  4. To unbind the triggered event use jQuery off, to unbind the options event use setGridParam with event name and value to null.

To define a multiple event handlers use dot "." after the event and appropriate description. Bellow is a example:

When we define foren columns in the grid with method setFrozenColumns we need to use ResizeStop event to properly resize the frozen div element. Using triggered event approach save us a lot of additional code. Somewhere in the method we have the following definition:

$(grid).on('jqGridResizeStop.setFrozenColumns', function (e, w, index) {
  // here our code
});

When the developer defines his own ResizeStop event - they both will be executed. The recommended way to do this is to define it like this:

$(grid).on('jqGridResizeStop.develoerResize', function (e, w, index) {
  // here developer code.
});

List of events

Below is the list of "option" and triggered events. The name of every triggered event begin with jqGrid and is set below the option event.

Note

The first parameter of the triggered event is always event. It should be used before any other parameter. By example if the described parameters in options event are a,b,c - i.e event(a,b,c), in triggered event we need to use triggered_event(e, a, b, c)

Note

There are additional events, which are set in the grid methods - some as parameter and some not as parameter. The list of these events is into the description of the method.


afterInsertRow
jqGridAfterInsertRow

This event fires after every inserted row. This event does not fire if gridview option is set to true

parameters

  • string rowid - is the id of the inserted row
  • array rowdata - is an array of the data to be inserted into the row. This is array of type name: value, where the name is a name from colModel.
  • mixed rowelem is the element from the response. If the data is xml this is the xml element of the row; if the data is json this is array containing all the data for the row.

beforeProcessing
jqGridBeforeProcessing

This event fire before processing the data from the server. If the event return false no data will be inserted into the grid and the old status remain as before the new request. This event fire only if ajax request is made - on paging on sorting and reloading and initially when the data is loaded. Note that the data is formatted depended on the value of the datatype parameter - i.e if the datatype is JSON for example the data is JavaScript object

parameters

  • mixed data - The data returned from the server, formatted according to the datatype
  • string status - a string describing the status
  • object xhr - object, which is a super set of the XMLHTTPRequest object.

beforeRequest
jqGridBeforeRequest

This event fire before requesting any data. Also does not fire if datatype is function. If the event return false the request is not made to the server

parameters

none


beforeSelectRow
jqGridBeforeSelectRow

This event fire when the user click on the row, but before select them. This event should return boolean true or false. If the event return true the selection is done. If the event return false the row is not selected and any other action if defined does not occur.

parameters

  • string rowid - is the id of the row.
  • event e - is the event object (original event)

gridComplete
jqGridGridComplete

This fires after all the data is loaded into the grid and all other processes are complete. Also the event fires independent from the datatype parameter and after sorting paging and etc. Does not fire if datatype is a defined as function.

parameters

none


loadBeforeSend
jqGridLoadBeforeSend

A pre-callback to modify the XMLHttpRequest object (xhr) before it is sent. Use this to set custom headers etc. Returning false or stop will cancel the request. This event is used in jQuery beforeSend event which is predefined in jqGrid.

parameters

  • object xhr - object, which is a superset of the XMLHTTPRequest object.
  • object settings - ajax settings object

loadComplete
jqGridLoadComplete

This event is executed immediately after every server request. The data can be or can not be loaded into the grid.

parameters

  • mixed data - data from the response depending on datatype grid parameter

loadError
jqGridLoadError

A function to be called if the request fails. This event is predefined in jQuery error event.

parameters

  • object xhr - The XMLHttpRequest object
  • string status - a string describing the type of error (status) that occurred
  • object error - an optional exception object (error), if one occurred.

onCellSelect
jqGridCellSelect

Fires when we click on particular cell in the grid. This event does not fire when cell editing is used on editable cell. (grid options cellEdit : true). It fire on non editable cell only independent of cellEdit flag.

parameters

  • string rowid - is the id of the row
  • int iCol - is the index of the column starting from 0
  • string cellcontent - is the content of the cell,
  • object e - is the event object element where we click.

ondblClickRow
jqGridDblClickRow

Raised immediately after row was double clicked.

parameters

  • string rowid - is the id of the row
  • int iRow - is the index of the row (do not mix this with the rowid)
  • int iCol - is the index of the column starting from 0
  • object e - is the event object element where we click.

onHeaderClick
jqGridHeaderClick

Fire after clicking the button on the caption to hide or show grid. Caption and hidegrid:true grid parameters should be set in order to use this event.

parameters

  • string gridstate - is the state of the grid - can have two values - visible or hidden
  • object e - event object when click the button.

onInitGrid
No triggered event available

The event fire when the grid is constructed and before loading the data into the grid. This event executes only once and is first in the order of all other grid events.

parameters

none


onPaging
jqGridPaging

This event fires after click on [page button] and before populating the data. Also works when the user enters a new page number in the page input box (and presses [Enter]) and when the number of requested records is changed via the select box. If this event return 'stop' the processing is stopped and you can define your own custom paging.

parameters

  • string pgButton - depending on the button clicked or inputing a number the parameter can be first,prev,next,last, records and user
  • object elem - html element object which corresponding to the button clicked.

onRightClickRow
jqGridRightClickRow

Raised immediately after row was right clicked. Usefull for context defined menus. Works on browsers which supports oncontextmenu event.

parameters

  • string rowid - is the id of the row
  • int iRow - is the index of the row (do not mix this with the rowid)
  • int iCol - is the index of the column starting from 0
  • object e - is the event object element where we click.

onSelectAll
jqGridSelectAll

This event fires when multiselect option is true and you click on the header checkbox to select/deselect current grid rows.

parameters

  • array aRowids - array of the selected rows (rowid's). This parameter contain the id of the rows in case there is selection and is empty array when nothing is selected.
  • boolean status - variable determining the status of the header check box - true if checked, false if not unchecked.

onSelectRow
jqGridSelectRow

Raised immediately after row was clicked.

parameters

  • string rowid - is the id of the row,
  • boolean status - is the status of the selection. Can be used when multiselect is set to true. true if the row is selected, false if the row is deselected.
  • object e - is the event object when clicked.

onSortCol
jqGridSortCol

Raised immediately after sortable column was clicked and before sorting the data. If this event return 'stop' the processing is stopped and you can define your own custom sorting using the methods setGridParam and .trigger('reloadGrid')

parameters

  • string sortname - is the index or name from colModel which sort is aplied,
  • int iCol - is the index of column start from 0,
  • string sortorder - is the new sorting order - can be 'asc' or 'desc'.

rowattr
jqGridRowAttr

This event is called when the new grid row is inserted. It can be used to set additional style and class attributes of the row dynamically. The event should return a object something like this {"style" : "somestyle", "class": "someclass"}. Note that you can set any attribute to the row. It is important to note that the event does fire only when a new row is inserted - this mean that it can not be used with methods which updated the row like setRowData.

parameters

  • array rowData - is array with the cell data.
  • mixed currObj - is the current row represented in the source like json or xml depending on the datatype parameter. - string rowId - is the id of the row.

resizeStart
jqGridResizeStart

Event which is called when we start resize a column.

parameters

  • object event - is the event object,
  • int index - is the index of the column in colModel stating from 0

resizeStop
jqGridResizeStop

Event which is called after the column is resized.

parameters

  • string newwidth - is the is the new width of the column,
  • int index - is the index of the column in colModel starting from 0

serializeGridData
No triggered event available

If set this event can serialize the data passed to the ajax request. The function should return the serialized data. This event can be used when a custom data should be passed to the server - e.g - JSON string, XML string and etc. The event actually is used in ajax data parameter.

parameters

  • object postData - object with parameters passed to the server.

Methods


This chapter describes the basic methods of jqGrid. Other methods related to TreeGrid, Subgrid, Editing modules and etc. are described into the appropriate chapters.

As of version 3.6 jqGrid uses new API which is compatible with jQuery UI library. This is a preferd API to use.

Calling Convetions

  • New API
<script>
...
jQuery("#grid_id").jqGrid('method', parameter1,...parameterN );
...
</script>

Where:

  • grid_id is the id of the already constructed grid.
  • jqGrid is a jqGrid instance.
  • method is jqGrid existing method. Note that the method should be enclosed in ''
  • parameter1,…parameterN - a list of parameters

Where a method is not designed to return a requested value, then what is returned is the jqGrid object and a set of such methods can be chained, e.g.,

<script>
...
jQuery("#grid_id").jqGrid('setGridParam',{...}).jqGrid('hideCol',"somecol").trigger("reloadGrid");
...
</script>
  • Old API
<script>
...
jQuery("#grid_id").jqGridMethod( parameter1,...parameterN );
...
</script>

Where:

  • grid_id is the id of the already constructed jqGrid.
  • jqGridMethod is a method applied to this jqGrid.
  • parameter1,…parameterN - a list of parameters

Note

The old and new APIs are enabled by default so that existing users do not have to change their code. You are free to use both conventions. The reason for creating this API is to overcome and name-space conflicts with other plugins and make using jqGrid more natural in the code. In order to use only this new API see the configuration below.

Configure Guriddo jqGrid to use the new API

To use only the new API (see below) set the jQuery.jgrid.no_legacy_api variable to true like this:

...
<script src="js/jquery.min.js" type="text/javascript"></script>
<script src="js/trirand/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="js/trirand/jquery.jqGrid.min.js" type="text/javascript"></script>
<script type="text/javascript">
    jQuery.jgrid.no_legacy_api = true;
</script>
...

Method list

Note

Parameters set without [] are required. Parameters enclosed in [] have default values and are not requiered.
In case the first or other parameter should be omitted set undefined or just look at the default value and set it.


addJSONData(array data)1
Populates a grid with the passed data (an array) at once clearing the old one if available.

parameters

  • array data - array of object that contain data to be inserted into the grid.

return
none
- - -
addLocalData( [boolean returnAll])1
Return a object containing grid data depending on search sorting, paging and etc. parameters, when the datatype is set to 'local'.

parameters

  • boolean returnAll - when set to true all the data is returned, otherwise returned rows depend on the rowNum paramer set.

return
object with data


addRowData(string rowid, mixed data, [string position], [string srcrowid])
Inserts a new row with id = rowid containing the data in data (an object) at the position specified (first in the table, last in the table or before or after the row specified in srcrowid). The syntax of the data object is: {name1:value1,name2: value2…} where name is the name of the column as described in the colModel and the value is the value.
This method can insert multiple rows at once. In this case the data parameter should be array defined as
[{name1:value1,name2: value2…}, {name1:value1,name2: value2…} ] and the first option rowid should contain the name from data object which should act as id of the row. It is not necessary that the name of the rowid in this case should be a part from colModel.

parameters

  • string rowid - the id for the new inserted row
  • mixed data - array or object with the data
  • string position - where to insert the row ('first', 'last') in the grid or 'before' 'after' a srcrowid. Default is last
  • string srcrowid - set the id of the row from where to insert the new one (after, before)

return
true on success, false otherwise


addXmlData(xml data)1
Populates a grid with the passed XML data.

parameters

  • xml node data - data to be inserted into the grid.

return
none
- - -
bindKeys([object settings])
Add scrolling functionality with arrows keys making it possible to scroll through the rows, there the current row is selected.

parameters

  • object settings - list of options with following properties and default values:
settings = {
  onEnter: null,
  onSpace: null,
  onLeftKey: null,
  onRightKey: null,
  scrollingRows : true
}

onEnter - event which occur when a Enter key is pressed of the current selected row
onSpace - event which occur when a Space is pressed of the current selected row
onLeftKey - event which occur when a Left key is pressed of the current selected row
onRightKey - event which occur when a Right key is pressed of the current selected row
scrollingRows boolean which determine if the grid should scroll when a row is in invisible due to the height limitation.

To the events the row id is passed as parameter.

The above events can be overwriten with trigered events which names are:
jqGridKeyEnter, jqGridKeySpace, jqGridKeyLeft, jqGridKeyRight

return
jqGrid object


clearGridData([boolean clearfooter])
Clears the currently loaded data from grid. If the clearfooter parameter is set to true, the method clears the data placed on the footer row.

parameters

  • boolean clearfooter - if set to true clears the footer data of the grid too. Default false.

return
jqGrid object


delRowData(string rowid)
Deletes the row with the id = rowid. This operation does not delete data from the server.

parameters
- string rowid - id of the row to be deleted.

return
true on success, false otherwise


footerData([string action], [object data], [boolean format])
This method gets or sets data on the grid footer row. When set data in the footer row, the data is formatted according to the formatter (if defined) in coModel. The method can be used if footerrow option is set to true.

parameters

  • string action - can be 'get' or 'set'. The default is get. 'get' returns an object of type name:value, where the name is a name from colModel. This will return data from the footer. The other two options have no effect in this case. 'set' takes a data object and places the values in the footer The value is formatted according to the definition of the formatter in colModel - see next parameter. The object should be in name:value pair, where the name is the name from colModel
  • object data - data to be set in the footer
  • boolean format - default is true. This instruct the method to use the formatter (if set in colModel) when new values are set. A value of false will disable the using of formatter

return
jqGrid object


destroyFrozenColumns()
Destroys the frozen column functionality set with setFrozenColums. For more information see Frozen columns

parameters
none

return
jqGrid object


getCell( string rowid, mixed iCol)
Returns the content of the cell specified by id = rowid and column = iCol. iCol can be either the column index or the name specified in colModel.

Attention

Do not use this method when you are editing the row or cell. This will return the cell content and not the actuall value of the input element

parameters

  • string rowid - row id of the grid where to edit a cell
  • mixed iCol - can be either the column index (integer - start from 0) or name specified in colModel.

return
string - html content of the cell.


getCol(mixed colname, [boolean rerurntype], [string mathoperation])
This method returns an array with the values of the grid column or a scalar value of operation set in mathoperation parameter.

parameters

  • mixed colname - can be either a number that represents the index of the column or a name from colModel.
  • boolean returntype determines the type of the returned array. When set to false (default) the array contain only the values. When set to true the array contain a set of objects. The object is defined as {id:rowid, value:cellvalue} where the rowid is the id of the row and cellvalue is the value of the cell. For example, such output can be [{id:1,value:1},{id:2,value:2}…]
  • string mathoperation - valid option for this parameter can be sum, avg, count, min, max . If this parameter is set and is valid, the returned value is a scalar representing the operation applied to the all values in the column. If the parameter is not valid the returned value is empty array

return
array or value depending mathoperation.


getColProp( string colname)
Return an array of the properties of the given column name from colModel

parameters

  • string colname - name of the column from colModel

return
object with column properties, if not found empty opbect


getDataIDs()
Return an array of the id's in the current grid view. It returns an empty array if no data is available.

parameters

none

return
array


getGridParam([string name], [string module])
Returns the value of the requested parameter from the grid options and other grid methods. If the name is not set, the entry grid options are returned.

parameters

  • string name - the name from the options array.
  • string module - module from which we ask the values of parameters. Default is jqGrid. The possible values are: jqGrid for jqGrid options, filterToolbar for filter toolbar search options, formProp certain options from editGridRow method, viewProp certain options from viewGridRow method, navGrid - all the options from navGrid method, inlineNav - all the options from inlineNav method,

return
object or scalar value


getGridRowById( string rowid)
Return the row with id = rowid as document object

parameters

  • string rowid - id of the grid row

return
row as document object


getInd(string rowid, [boolean rowcontent])

Returns the index of the row in the grid table specified by grid id row - rowid. If rowcontent is set to true it returns the row document object

parameters

  • string rowid - the id of the grid row.
  • boolean rowcontent - if set to true the method return document row object. Default is false.

return
mixed - index of the row or document row object.


getLocalRow( string rowid)
Return the row data object from the local array stored in data parameter when the datatype is local.

parameters

  • string rowid - the id of the grid row.

return
mixed - object if found, false is not found


getRowData( [string rowid], [boolean usedata] )
Returns an object or array (see below) with data of the requested id = rowid. The returned object is of type name:value, where the name is a name from colModel and the value from the associated column in that row. It returns an empty object if the rowid can not be found. If the rowid is not set the method return all the data from the grid view as array which elements are objects.

parameters

  • string rowid - the id of the grid row.
  • boolean usedata - if set to true the data is get from the local grid parameter data and not from the grid view. Default is false.

Attention

Do not use this method when you are editing the row or cell. This will return the cell html content and not the actual value of the input element.


hideCol( mixed colname(s) )
Given a single colname, it hides the column with that name. Given an array of colnames ['name1','name2'], it hides the columns with those names, 'name1' and 'name2', in the example. The names in colname or colnames must all be valid names from the colModel.

parameters

  • mixed colname - can be either name form colModel or a array with column names from colModel.

return
jqGrid object


progressBar( [object settings] )
Show/hide the loading box with message which indicates a processing. The method is used internally in jqGrid when a request begin (show the box) and end (hide the box)
parameters

  • object settings - object containing following properties with default values:
settings = {
  htmlcontent : "",
  method : "hide",
  loadtype : "disable"
}

htmlcontent - the string which will be displayed when box shows
method - 'show' or 'hide'
loadtype - have the same values and behavior as loadui grid parameter - 'disable', 'enable', 'block'

return
jqGrid object


remapColumns(array permutation, [boolean updateCells] , [boolean keepHeader])
Reorder the grid columns based on the permutation array. The indexes of the permutation array are the current order, the values are the new order. By example if the array has values [1,0,2] after calling this method the first column will be reordered as second. updateCells if set to true will reorder the cell data. keepHeader if set to true will reorder the data above the header cells.

parameters

  • array permutation - array with the new column order
  • boolean updateCells - if set to true updates the data cels . Default false

return
none


resetSelection()
Resets (unselects) the selected row(s). Works in multiselect mode. When called this method set the grid parameters selrow to null and selarrrow to empty array.

parameters

none

return
jqGrid object


resizeColumn (mixed column, string newWidth, boolean forceresize)
Resize column dynamically to the newWidth simulating re-sizing with the mouse.

parameters

  • mixed colname - if string it should equal to the name of colModel. Can be number representing the index in colModel.
  • string newWidth - the new width in pixels to which the column will be re-sized.
  • boolean forceresize - when set to true the column is resized independed form the colModel option resizable - i.e the column is resied in all cases

return
jqGrid object


resizeGrid( [integer timeout] )
Resize the grid width of the parent container width. The method is useful to be used when the window width changes dynamically.

parameters

  • integer timeout - timeout in milliseconds in setTimeout function which is called when the grid is re-sized. Default is 500

return
jqGrid object


setCaption(string caption)
Sets a new caption of the grid Caption layer. If the Caption layer was hidden, it is shown.

parameters
- string caption - new caption to be setCaption

return
jqGrid object


setCell(string rowid, string colname, [string data], [mixed class] ,[object properties],[boolean forceup])
Change the content of particular cell and can set class or style properties.

parameters

  • string rowid - the is of the grid row
  • string colname - column name as defined in colModel or index staring from 0
  • string data - the new data that will be set. If empty string the content will not be changed
  • mixed class - if the class is a string we set it as class. If the class is object we set the properties with the css jQuery method
  • object properties - attribute properties to be set
  • boolean forceup - if the parameter is set to true we perform update of the cell instead that the data parameter is empty.

return
jqGrid object


setColProp( string colname, object properties)
Sets new properties in colModel. This method can dynamically change properties of the column. Note that some properties can not be changed - like width.

parameters

  • string colname - the name of the column from colModel name property.
  • object properties - new column properties to be set.

return
jqGrid object


setFrozenColumns()
Enables frozen columns in grid. See frozen columns. Also see method destroyFrozenColumns

parameters

none

return
jqGrid object


setGridHeight(string newheight)
Sets the new height of the grid dynamically. The height is set only to the grid cells and not to the entrie grid.

parameters

  • string newheight - the new height which can be pixels (no px at end), percentage or 'auto'

return
jqGrid object


setGridParam( object newparams, [boolean overwrite])
Sets a particular parameter. For some parameters to take effect a trigger("reloadGrid") should be executed. Note that with this method events can be overwriten. The name (in the name:value pair) is the name from options array.

parameters

  • object newparams - the object that contain the new value(s) of parameters.
  • boolean overwrite - if set to true the grid parameters are overwriten and are set with $.extend({}, gridparams, newparams);. The default is false where the parameters are extended with $.extend(true, gridparams ,newparams);

return
jqGrid object


setGridState( string state)
Show or hide the grid depending and state parameter. When the state is set to 'visible' the grid will be shown. When the parameter is set to 'hidden' the grid will be hidden. Note that the method does not call onHeaderClick event and the caption of the grid is allway visible.

parameters

  • string state - 'visible' or 'hidden'

return
jqGrid object


setGridWidth(string newwidth, [boolen shrink])
Sets a new width to the grid dynamically

parameters

  • string newwidth - the new width in pixels
  • boolean shrink - has the same behavior as shrinkToFit - see options. If this parameter is not set the value of shrinkToFit is get.

return
jqGrid object


setLabel(string colname, [string label], [mixed class], [object properties])
Sets a new label in the header for the specified column; can also set attributes and classes

parameters
- string colname - the name of the column from colModel. The parameter can be a number (the index of the column) beginning from 0
- string label - the content that can be put into the label. If empty string the content will not be changed
- mixed class - if class is string then the class to the label is added via addClass; if class is an object the new css properties are set via css jQuery method.
- object properties - sets the attribute properies of the label.

return
jqGrid object


setRowData(string rowid, [object data], [mixed cssprop])
Updates the values (using the data object) in the row with id = rowid.

parameters

  • string rowid - the id of the row to be updated
  • object data - The syntax of data object is: {name1:value1,name2: value2…} where the name is the name of the column as described in the colModel and the value is the new value.
  • mixed cssprop - If the cssprop parameter is string addClass is used to add classes to the row. If the parameter is object jQuery css method is used to add css properties. Properties and classes can be set without data, in this case data should be set to false.

return
boolen true on success, false otherwise.


setSelection(string rowid, [boolean onselectrow])
Toggles a selection of the row with id = rowid; If selected the selrow grid parameter is set to the rowid - in multiselect mode to selarrrow array is added the rowid. The revers if the row is deselected.

parameters
- string rowid - the id of the row
- boolean onselectrow - if onselectrow is true (default) then the event onSelectRow and/or triggered event jqGridSelectRow are launched, otherwise not.

return
jqGrid object


setSortIcon(mixed column, [string position])
The method changes the position of the sort icon at left or right depending on the position parameter.

parameters

  • string column - the column name or the position of the column in colModel starting from zero.
  • string position - left or right. default right.

return
jqGrid object


showCol( mixed colname )
Shows a column with a given colname. If the colname is a string we show only the specified column. If colname is array of type ["name1","name2"] then the columns with names 'name1' and 'name2' will be shown at the same time The names in colname must be valid names from colModel. The width does not change.

parameters

  • mixed colname - string or array of names from colModel

return
jqGrid object


sortGrid( [string colname], [boolean reload], [string sortorder])
Sort the the grid by the given colname and shows the appropriate sort icon.

parameters

  • string colname the name of the column from index property of colModel. If not found the name property is searched. If the parameter is set as false or undefined the colname equal to the current value of sortname parameter from grid options.
  • boolean reload - If the reload is set to true, the grid reloads with the current page and sortorder settings. Default is false.
  • string sortorder - set the sortorder for the sorting can be asc or desc.

return
jqGrid object


trigger("reloadGrid")
Reloads the grid with the current settings. This means that a new request is send to the server if datatype is xml or json. This method should be applied to an already-constructed grid. Pay attention that this method does not change HEADER information, that means that any changes to colModel would not be affected.

parameters

none

return
none


unbindKeys()
Unbind the events defined in bindKeys method.

parameters
none

return
jqGrid object


  1. These methods require special calling. The new API can't be used. To use the methods get the grid instance as variable this way:
    var mygrid = jQuery("#grid_id")[0];
    var mydata = JSON.parse( some_response );
    mygrid.addJSONData(mydata);