This is an old revision of the document!


Methods

This chapter describes the basic methods of jqGrid. Some methods require that additional modules should be loaded.
As of version 3.6 jqGrid uses new API which is compatible with jQuery UI library. See below. See also jqGrid Events.

Calling Convention:

<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

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").setGridParam({...}).hideCol("somecol").trigger("reloadGrid");
...
</script>

or using the 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

Having this our example will look like this:

<script>
...
jQuery("#grid_id").jqGrid('setGridParam',{...}).jqGrid('hideCol',"somecol").trigger("reloadGrid");
...
</script>
It is important to note that the existing users cannot 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.

Configuring jqGrid to use only the new API

This should be done in the installation procedure following these steps:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My First Grid</title>
 
<link rel="stylesheet" type="text/css" media="screen" href="css/ui-lightness/jquery-ui-1.7.1.custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="css/ui.jqgrid.css" />
 
<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script type="text/javascript">
	jQuery.jgrid.no_legacy_api = true;
</script>
<script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>
 
</head>
<body>
...
</body>
</html>

Note the callling of

<script type="text/javascript">
	jQuery.jgrid.no_legacy_api = true;
</script>

This line should be after the language file and before the jqGrid JS file

Method names in green require special calling procedures. See the individual method descriptions for example usage.
MethodParametersReturnsDescription
addJSONDatadatanonePopulates a grid with the passed data (an array).This method should be used this way - Example: Suppose we have data from a particular webservice (jsonresponse), then
var mygrid = jQuery(“#”+grid_id)[0];
var myjsongrid = eval(“(”+jsonresponse.responseText+“)”);
mygrid.addJSONData(myjsongrid);
myjsongrid = null;
jsonresponse =null;

will populate the data to the grid. And, of course, the data in myjsongrid can be manipulated before being passed to addJSONData.
addRowDatarowid,
data,
position,
srcrowid
true on success,
false otherwise
Inserts a new row with id = rowid containing the data in data (an array) 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 array is: {name1:value1,name2: value2…} where name is the name of the column as described in the colModel and the value is the value.
addXMLDatadatanonePopulates a grid with the passed data. This method should be used this way - Example:
Suppose we have data from a particular webservice (xmlresponse), then
var mygrid = jQuery(“#”+grid_id)[0];
mygrid.addXmlData(xmlresponse.responseXML);

will populate the data into the grid. And, of course, the data in xmlresponse can be manipulated before being passed to addXmlData.
clearGridDataclearfooterjqGrid object 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.
delRowDatarowidtrue on success,
false otherwise
Deletes the row with the id = rowid. This operation does not delete data from the server.
footerDataaction,
data,
format
jqGrid objectThis method gets or sets data on footer. See footerrow in options array.
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 array (object) and places the values in the footer. The object should be in name:value pair, where the name is the name from colModel
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
getCellrowid,
iCol
cell content 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.
Do not use this method when you editing the row or cell. This will return the cell content and not the actuall value of the input element
getColcolname, returntype, mathoperationarray[] or value This method returns an array with the values from the column. colname can be either a number that represents the index of the column or a name from colModel. 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}…]
The valid options for mathoperation are - 'sum, 'avg', 'count'. 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
getDataIDsnonearray[]This method returns an array of the id's in the current grid view. It returns an empty array if no data is available.
getGridParamnamemixed valueReturns the value of the requested parameter. name is the name from the options array. If the name is not set, the entry options are returned. For available options, see options.
getIndrowid,
rowcontent
mixed This method returns the index of the row in the grid table specified by id= rowid when rowcontent set to false (default). If rowcontent is set to true, it returns the entry row object. If the rowid can not be found, the function returns false.
getRowData rowid or nonearray{}Returns an array with data of the requested id = rowid. The returned array 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 array if the rowid can not be found.
Do not use this method when you editing the row or cell. This will return the cell content and not the actuall value of the input element
If the rowid is not set the method return all the data from the grid in array
hideColcolname
or
[colnames]
jqGrid objectGiven 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.
NB: The width of the grid is not changed.
remapColumnspermutation, updateCells, keepHeadernoneReorder 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.
resetSelectionnonejqGrid objectResets (unselects) the selected row(s). Also works in multiselect mode.
setCaptioncaptionjqGrid objectSets a new caption of the grid. If the Caption layer was hidden, it is shown.
setCellrowid,
colname,
data,
class,
properties
jqGrid objectThis method can change the content of particular cell and can set class or style properties. Where:
rowid the id of the row,
colname the name of the column (this parameter can be a number (the index of the column) beginning from 0
data the content that can be put into the cell. If empty string the content will not be changed
class if class is string then we add a class to the cell using addClass; if class is an array we set the new css properties via css
properties sets the attribute properies of the cell
setGridParamobjectjqGrid objectSets a particular parameter. Note - for some parameters to take effect a trigger(“reloadGrid”) should be executed. Note that with this method we can override events. The name (in the name:value pair) is the name from options array. For a particular options, see options.
setGridHeightnew_heightjqGrid objectSets the new height of the grid dynamically. Note that the height is set only to the grid cells and not to the grid. new_height can be in pixels, percentage, or 'auto'.
setGridWidthnew_width,
shrink
jqGrid objectSets a new width to the grid dynamically. The parameters are:
new_width is the new width in pixels.
shrink (true or false) has the same behavior as shrinkToFit - see options. If this parameter is not set we take the value of shrinkToFit.
setLabel colname,
data,
class,
properties
jqGrid objectSets a new label in the header for the specified column; can also set attributes and classes . The parameters are:
colname the name of the column (this parameter can be a number (the index of the column) beginning from 0
data the content that can be put into the label. If empty string the content will not be changed
class if class is string then we add a class to the label using addClass; if class is an array we set the new css properties via css
properties sets the attribute properies of the label
setRowDatarowid,
data,
cssprop
true on success,
false otherwise
Updates the values (using the data array) in the row with rowid. The syntax of data array 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.
If the cssprop parameter is string we use addClass to add classes to the row. If the parameter is object we use css to add css properties. Note that we can set properties and classes without data, in this case we should set data to false
setSelectionrowid,
onselectrow
jqGrid objectToggles a selection of the row with id = rowid; if onselectrow is true (the default) then the event onSelectRow is launched, otherwise it is not.
showColcolnamejqGrid objectShows 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.
trigger(“reloadGrid”)nonenone 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. You should use gridUnload to reload new configuration with different colModel
updateColumnsnonenonethis synchronizes the width of the headers with the data. Useful when used with table drag and drop. This method should be used this way - Example:
var mygrid=jQuery(“#grid_id”)[0];
mygrid.updateColumns();

Common functions and settings

These functions can be used anywhere in the project and are not related to the jqGrid object. This mean the the syntax is:

<script>
...
jQuery.jgrid.jqGridFunction( parameter1,...parameterN );
...
</script>

Where:

  • jgrid.jqGridFunction is a function.
  • parameter1,…parameterN - a list of parameters


Note the namespace jgrid


Function/OptionParametersReturnsDescription
ajaxOptionsempty objectnoneThis option allow to set global ajax settings for all ajax requests used in the grid. Note that with this option is possible to overwrite all current ajax setting for the particular module. Starting from version 3.6 we have a 3 level ajax settings.
The first level is specific for the module when we use ajax.
The second level is determined from this option, and the
third level can be passed as additional parameter for the particular method. The third level ajax setting has a higher priority. This means that we use this global rule for all ajax settings:
jQuery.extend(jQuery.ajax({method specific options}, ajaxOptions, ThirdLevelajaxSettinds));
Additional to this we have a possibility to define on every ajax request serialize function which allow to convert the parameters passed to the server.
jqIDstringparsed stringEscapes the special string characters with two backslashes (\\) so that a single backslash will be put into the string and can be interpreted correct when used in jQuery selector.
jgrid.htmlDecodestringdecoded_string The htmlDecode function decodes an HTML encoded string back into the original html code.
jgrid.htmlEncodestringencoded_string The htmlEncode function encodes an HTML string - opposite to htmlDecode
jgrid.formatstringformated_string Simple string-templating. Accepts a string template as the first argument. The second is optional: If specified, it is used to replace placeholders in the first argument.
Example jQuery.jqgformat(“Please enter a value between {0} and {1}.”, 4, 8)
result : “Please enter a value between 4 and 8.”
jgrid.getCellIndexcell index This method is used to correct the bug in Internet Explorer versions ⇐ 7 where CellIndex is calculated in Display Order and not in real one. cell is the cell content (i.e.) td element
jgrid.stringToDocxmlstringxmlDoc Convert xmlstring to dom document. Return xmlDoc - dom document.
jgrid.stripHtmlcontentnew_contentFunction for stripping out HTML tags from a given content.
jgrid.parsejsonStringobjectThis function parses a jsonString (JSON text) to produce an object or array.
To prevent JavaScript hijacking attacks, web application authors are encouraged to use this function. This returns a JSON representation of the variable.
Cyclic structures are detected and safely interrupted, but could not be further restored.
1. The while(1); construct, located at the beginning of JSON text,
2. Comments at the beginning and end of the text.
JSON data providers are encouraged to use one or both of these methods to prevent data execution. Such JSON response may then look like this
while(1);/*{[
{“name”:“safe value 1”},
{“name”:“safe value 2”}, …
]}*/
jqGrid uses this function when obtaining a data with datatype:'json'

Add on Grid Methods

To use these methods you will need to mark Custom checkbox when downloading the grid See download. For developers - these method are located in file grid.custom.js. These methods should be used as those described in Chapter 1 - i.e that are jqGrid methods.

MethodParametersReturnsDescription
filterGridgrid_id,
params
HTML objectThis method can be called to construct an custom search form for the grid and should be not applied to the grid but to a valid HTML element.
grid_id is the id of the grid to which the search will be applied.
parms is an array of parameters (see below). For more details refer to custom searching
filterToolbarparamsjqGrid objectThis method is the same as filterGrid, except that the search input elements are placed in the grid just below the header elements. When the header elements are resized the input search elements are also resized according to the new width. Another difference to the filterGrid is that the filter toolbar uses definitions from colModel. For more information refer to Toolbar searching
getColPropcolnamearray{}Return an array of the properties of the given column name from colModel
GridDestroygrid_idtrue on success,
false otherwise
Destroys the entry grid with id= grid_id from the DOM (clears all the html associated with the grid and unbinds all events)
GridUnloadgrid_idtrue on success,
false otherwise
The only difference to previous method is that the grid is destroyed, but the table element and pager (if any) are left ready to be used again.
setGridStatestatejGrid objectShow 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
setColPropcolname,
properties
jGrid objectSets new properties in colModel. This method is ideal for dynamically changing properties of the column. Note that some properties - have no effect see colModel options. For example:
jQuery(“#grid_id”).setColProp('colname',{editoptions:{value:“True:False”}});
will change the editoptions values.
sortGridcolname,
reload
jqGrid objectSorts the given colname and shows the appropriate sort icon. The same (without sorting icon) can be done using setGridParam({sortname:'myname'}).trigger('reloadGrid'). If the reload is set to true, the grid reloads with the current page and sortorder settings.
updateGridRowsdata,
rowidname,
jsonreader
true on success,
false otherwise
This method update the existing data in the grid by given rowidname.
data is a array of data in format
[{name:value,name1:value1…}, {name:value,name2:value2…}]
where the name is the name from colModel and value is the actuall value. It is not neccessary that all columns are present in the data item object (the same as setRowData method)
rowidname (string) - is the name of the row which should acts as id If not set the name “id” is used.
jsonreader (boolean) default false. If set to true a jsonReader definition is used to set the data. Note that this work only if the item in jsonReader object 'repeatitems' is set to true.In this case the data should be not in pair name:value, but only values where the number of columns should be equal of those in colModel.

Discussion

vj, 2010/02/01 20:25

How can I submit all the grid to the server at once. Any help would be greatly appreciated.

Ariel E Novo Rijo, 2010/03/03 19:57

Hi everyone. Any idea how can i pass parameters to the url invoked by the grid ?

Zivko Sudarski, 2010/03/11 17:31, 2010/03/11 17:33

How can I submit all the grid to the server at once. Any help would be greatly appreciated ?


example: ( jQuery ) onSubmit Click function : $(”#buttonId”).click(function(){

 //get total rows in you grid
 var numberOfRecords = $("#gridId").getGridParam("records");
 for(i=1;i<=numberOfRecords;i++)
{
	
	var rowId = $("#gridId").getRowData(i);
	var name = rowId['name'];
              
              //put all rows for your grid
              .
              .
	$('<input type="hidden" />').attr('name', i+'_name').attr('value',ime).appendTo('#hiddenDivId');
}

});

Now, you can read hidden value, on your form submit.

Alvin zeng, 2010/03/17 02:34, 2010/03/17 02:35
  You can post all datas like this way:
———————–
  var rows= jQuery("#jqgrid_id").jqGrid('getRowData');
  var paras=new Array();
  for(var i=0;i<rows.length;i++){
      var row=rows[i];
      paras.push($.param(row));
  }
  $.ajax({
      type: "POST",
      url: "/someurl.do",
      data: paras.join('and'),
      success: function(msg){
          alert(msg);
      }
  });
zbacsi, 2010/08/30 18:05

The getRowData method returns only the visible rows from the grid.

Erwin Komaruloh, 2010/06/15 03:32

Hi,

I was wondering if I can put some search option when I use trigger('reloadGrid') method? Like reload only rows where some field is matched to some condition.

Thanks before,

Zuvko Sudarski, 2010/10/20 21:52

Hi, you can setGridParam url , and then reload grid. With new url, you can get data you want to show.

$(”#grid”).setGridParam({url:'url'}); $(”#grid”).trigger(“reloadGrid”);

Mike Naughton, 2011/01/12 16:44

Hi,

Is there a way for JavaScript to know which page the grid currently thinks it's on? I would like my page to do some things if the grid is on page 1, but not if it is on another page.

Thank you,

Giorgio, 2011/02/03 17:37, 2011/02/03 18:17

Hi, I've a JqGrid with Json Data mapped in, I want to know if there is a method to change data on the fly… I call an action method via Ajax that return Json Data (the same mapped in jqGrid), so now i want to change the data via jqgrid methods like

$(”#grid”).setGridParam('data',mydata);

Thanks…

SOLVED


I've to use addJSONData!

Sorry… the documentation had to be always read entirely!!

jay ann patangan, 2011/03/17 06:25

hi, good day. is there a way that i can get the location or path of the url that reads my data from the server? i want to display it in my html. i have this code:..

  $("#btnQuery").click( function() {
     var params = {
        "ID": $("#eSessionID3").val(),
        "Type": "data"
     }
     var url = 'some.php?path=' + encodeURI('some/data') + '&json=' + encodeURI(JSON.stringify(params));
     $('#tblData').setGridParam({
  url:url, 
  datatype: primeSettings.ajaxDataType,  
     });
     $('#tblData').trigger('reloadGrid');   
     $('#firstur').append('the url: ' + url+'<br>');
     $('#secur').append('response: ' + url+'<br>');
  });

my some.php code is something like this:

  <?php 
echo(file_get_contents("http://localhost/" . $_GET["path"] . "?json=" . $_GET["json"]));
  ?>

questions? 1. i want to display/alert the location or path of the url that reads/loads my data from the server?

in firebug console, it's something that looks like this:

http://localhost/..../some.php?path=some/data/&json=%7B%22ID%22:%22PK0hyW%22,%22dataType%22:%22data%22%7D& json={%22ID%22:%22PK0hyW%22,%22dataType%22:%22data%22,%22recordLimit%22:5,%22recordOffset%22:0,%22rowDataAsObjects%22:false,%22queryRowCount%22:true,%22sort_fields%22:%22main_account_group_desc%22}

2. i want to get and display/alert the response body of the url?

is ther anybody here who knows the answer. thank you

Daniel, 2011/08/02 13:09

An error on the page. in the method column incorect addXMLData corect addXmlData

Anthony White, 2011/10/12 20:15, 2011/10/12 20:16

There appears to be an undocumented parameter for the sortGrid method. It can also take a sort order as the last parameter, which can be 'asc' or 'desc', as the grid tends to use throughout. It seems to default to 'asc'.

Dinusha De Silva, 2011/11/02 05:29

Hi,

  I have a select element in my add record dialog. the values are saved successfully to the grid. now I need to get the values to save to the database. But when I try to get the values I get the display text of the selected value.

here's my colmodel:

name:'mpt_ReasonUID',index:'mpt_ReasonUID',width:110, editable: true,edittype:“select”,editoptions:{value:“FE:FedEx;TN:TNT”}}

i need to get the values like 'FE', 'TN'. but I get 'FedEx', 'TNT' by using jQuery(”#list_outcomeReasons”).jqGrid('getLocalRow', rowIDs[i]);

Shigang Liu, 2011/11/03 01:20

You can try to add “formatter:'select'” in your colmodel.

alnkapa, 2012/01/23 09:37

Hello It is possible to obtain the number of rows that fit into the current size of the parent before loading the data from the server?

Mikle, 2012/03/29 10:17

Hi, in description method hideCol ”… NB: The width of the grid is not changed.”

in code (function hideCol()) ”… if(fndh===true) {

$($t).jqGrid("setGridWidth",$t.p.shrinkToFit === true ? $t.p.tblwidth : $t.p.width );

} …”

in options shrinkToFit default is true

So, NB: The width of the grid will be changed, and it depends on shrinkToFit option.

Mikle, 2012/03/29 10:21

By the way, i think it's mistake in code. it must be: $($t).jqGrid(“setGridWidth”, $t.p.width );

Sovattha Sok, 2012/06/21 10:11

For those of you still stuck with the inability to save data locally instead of on a server with jqGrid, you can use the data proxy.

When instantiating the jqGrid:

$(”#myTable”).jqGrid({ … dataProxy: dataProxyFn, …});

then when opening your popup:

$(”#myTable”).jqGrid('editGridRow', “new”, { … useDataProxy: true …});

The argument url or editurl are not needed anymore.

Then this is my function dataProxyFn() which can be better but works currently:

function dataProxyFn(t) {

var lastId = 1;
if ($(this).getDataIDs().length > 0) {
	lastId = parseInt($(this).getDataIDs().length) + 1;
}
if (t.data.id == "_empty") {
	$(this).jqGrid("addRowData", lastId, t.data, "last");
} else {
	if (t.data.oper == "del") {
		$(this).jqGrid("delRowData", t.data.id);			
	} else {
		$(this).jqGrid("setRowData", t.data.id, t.data);
	}
}

}

Masud, 2012/08/17 15:55

I want to disable enter key after editing any cell. please help me with example code.

yiliZhou, 2012/10/23 10:05

I'm try to use hideCol to hide some column.But when I use formedit and the column is first of the row,all of the row's columns is hided. How can I to show column in form.my code:

	colModel:[{name:"id",index:"id",width:100,editable:false},
		{name:"name",index:"name",width:100,editable:true,formoptions:{colpos:1,rowpos:1}},
		{name:"hireDate",index:"hireDate",editable:true,formoptions:{colpos:2,rowpos:1}},
		{name:"birthday",index:"birthday",editable:true,edittype:"text",editoptions:{
		 dataInit:function(elem){
		initdate(elem);//initdatepicker
				} 	    	
			},formoptions:{colpos:3,rowpos:1}},
		{name:"department.id",index:"department.id",editable:true,formoptions:{colpos:1,rowpos:2}},
		{name:"mobilePhone",index:"mobilePhone",editable:true,formoptions:{colpos:2,rowpos:2}}
		]

… jgrid.jqGrid(“hideCol”,[“department.id”,”hireDate”]).trigger(“reloadGrid”);

… if I use this to hide department.id in grid.the row 2 all hided in form.

Randy Forbes, 2013/04/22 19:09

In v3.6 of jqGrid, a new API was introduced to avoid name-space conflicts. Are there any performance or other advantages to using the new API? Additionally, it states “You are free to use both conventions.” Will the old API be deprecated in a future release?

OLD API <script> … jQuery(”#grid_id”).setGridParam({…}).hideCol(“somecol”).trigger(“reloadGrid”); … </script>

NEW API <script> … jQuery(”#grid_id”).jqGrid('method', parameter1,…parameterN ); … </script>

Thanks.

Michael, 2013/04/23 10:57

addRowData currently only knows the position first, last, before and after. It would be nice to have a position sortorder which inserts the new data with respect to the current sort order. Also it would be helpfull if setCell and setRowData optionally would resort the table if necessary.

You could leave a comment if you were logged in.

QR Code
QR Code wiki:methods (generated for current page)