[Go] Introduction to jqgrid

Source: Internet
Author: User
Jqgridjqgrid is a table control built on jquery. It communicates with the server in Ajax mode.
Jqgrid demo is an Online Demo project. Here, we can know what jqgrid can do. Jqgrid is a jquery plug-in for processing table presentation. It supports paging, rolling loading, searching, locking, and dragging. The following describes how to organize jqgrid practices in recent projects:

1. introduce it to the Project

Jqgrid home page in the http://www.trirand.com/blog/, the above provides download, demo, Wiki and other documents, are more detailed. In particular, the http://www.trirand.com/jqgridwiki/doku.php is worth a lot of attention in development. Okay. After downloading the file, you need to introduce it to the project header file:

<link rel="stylesheet" type="text/css" href="$request.contextPath/script/jqGrid/css/ui.jqgrid.css" /> <script type="text/javascript" src="$request.contextPath/script/jqGrid/js/jquery.jqGrid.min.js"></script> <script type="text/javascript" src="$request.contextPath/script/jqGrid/js/i18n/grid.locale-cn.js"></script>

Jqgrid uses the CSS topic of jqueryui, You need to download the corresponding topic http://jqueryui.com/themeroller/ to find the corresponding topic download, if you use the datepicker control, you also need the UI. As follows:

<link rel="stylesheet" type="text/css" href="$request.contextPath/script/jqGrid/css/jquery-ui-1.8.22.custom.css" media="all"/> <script type="text/javascript" src="$request.contextPath/script/ui/jquery-ui-1.8.22.custom.min.js"></script> <script type="text/javascript" src="$request.contextPath/script/ui/jquery.ui.datepicker-zh-CN.js"></script>

 

2. Use

Two basic elements are required for VM and JSP on the page.

<Table id = "jqgridid"> </table> // This is required. <Div id = "pager"> </div> // This displays the page bar information, as needed

Then in JS

$("#jqGridId").jqGrid({options})

This is the most basic setting. The focus is on options, including basic parameter settings and functions. For details, see the documents on the Official Website:

Http://www.trirand.com/jqgridwiki/doku.php? Id = wiki: Options
Http://www.trirand.com/jqgridwiki/doku.php? Id = wiki: Methods

 

3. parameters (options)

Parameters refer to the jqgrid object to set properties of various features, specific settings in the http://www.trirand.com/jqgridwiki/doku.php? Id = wiki: Options

The following example lists common parameters and describes them:

$ ("# Jqgridid "). jqgrid ({URL: s2web. appurl + "JQ/queryware. action ", datatype:" local ", // Initialization is not loaded when it is local. mtype such as JSON and XML are supported:" Post ", colnames: ['number', 'author ', 'isbn ', 'weight', 'description'], // header colmodel: [// the attribute of the root object in jsonreader is parsed Based on the index, and the cell {Name: 'id', index: 'id', width: 55, align: "center", sortable: false}, {Name: 'author', index: 'author', width: 100, sortable: false}, {Name: 'isbn ', index: 'isbn', width: 120, align: "right", sortable: false}, {Name: 'weight', index: 'weight', width: 80, align: "center", sortable: false}, {Name: 'waredes', index: 'waredes', width: 400, sortable: false}], width: 'auto', // number & 'auto', '000000' Height: 100%, rownum: 5, // number of records per page rowlist: [5, 10, 20, 30], // optional list of records per page Pager: '# pager2', // page tag divid viewrecords: True, // display the number of records. If this parameter is set to false, recordtext is not displayed below: "records from {0} to {1}, total records from {2 ", // The default value is {0}-{1}. {2} scroll: false. // scroll through the page, if it is set to true, the page flip bar will not be displayed/** here is the default sorting setting. These values will overwrite */sortable: false, sortname: "warename", sortorder: "DESC", caption: "item list", // display the query result table title rownumbers: True, // set the display sequence number of the list, note that rn cannot be used as index rownumwidth: 20 in colmodel. // you can specify the width of the serial number. The default value is 25 multiselect: True. // select multiple boxes multiboxonly: True, // only one choice is supported when you click the table row. You can only select multiple items when you click checkbox. The value of multiselect = true is valid prmnames: {// if the current query object is ware, you can set page: "waredetail. page ", rows:" waredetail. rows ", sort:" waredetail. sidx ", order:" waredetail. sord ", search:" waredetail. search "}, jsonreader: {// The server returns the JSON parsing settings root:" list ", // For the JSON data list page:" page ", total:" totalpage ", records: "totalcount", repeatitems: false, }}); $ ("# jqgridid "). jqgrid ('navgrid', '# pager2' {EDIT: false, add: false, del: false, search: false}); // set the information displayed on the page bar.

The meanings of the above parameters have been described. For details, see the detailed introduction in the above document.

 

Prmnames:Each time these parameters are passed as request parameters to the server, they generally maintain paging, sorting, and other information. You can declare these attributes in the query object in a unified manner, which is consistent with the settings here. For example:

Public class jqgridquerybase implements serializable {Private Static final long serialversionuid =-2849625318771_4220l;/** current page */private int page;/** number of records per page */private int rows; /** query field value */private string search;/** sort fields and sorting methods such as username/ASC */private string sidx; private string sord; /** page information: Total number of records */private int totalcount;

Jsonreader:Like prmnames, It is a parsing method for interaction with the server in JSON format. The root element is a JSON array that parses elements in colmodel, while others involve paging and other information. For example, the object returned every time in the action is pagemodule, which can be defined:

Public class pagemodule <t> extends jqgridquerybase {Private Static final long serialversionuid =-663641770315885315l; /** query returned result data */private list <t> List = new arraylist <t> ();

Colmodel:Colmodel on the json array object how to parse the cell settings filled to the table, including the basic name, index, width, formater, etc., see the http://www.trirand.com/jqgridwiki/doku.php? Id = wiki: colmodel_options

For example:

  • Name: Set a unique name for each column in the grid. This is a required option. The reserved words include subgrid, CB, And RN.
  • Index: Set the index name used for sorting. This index name will be passed to the server as the sidx parameter (set in prmnames.
  • Label: When the colnames option array of jqgrid is empty, specify the header for each column. If both colnames and this item are empty, the name option value becomes the topic.
  • Width: Sets the column width. Currently, only values in PX are allowed. The default value is 150.
  • Sortable: Sets whether the column can be sorted. The default value is true.
  • Search: Set whether the column can be listed as a search condition. The default value is true.
  • Resizable: Sets whether the column size can be changed. The default value is true.
  • Hidden: Sets whether this column is hidden during initialization. The default value is false.
  • Formatter: Default type or custom function name used to format the column. Common preset formats include integer, date, currency, and custom.

The above parameter meaning comes from http://blog.csdn.net/jpr1990/article/details/6891115

For example, you can set prefix and split for the price as follows:

{name:‘price‘,index:‘price‘, width:80,align:"right", formatter:‘currency‘, formatoptions:{decimalSeparator:".", thousandsSeparator: ",", decimalPlaces: 2, prefix: "$"}},

Supports the following drop-down select Settings:

{Name: 'valid', index: 'valid', width: 100, align: "center", formatter: 'select', edittype: 'select', editoptions: {value: "0: spot; 1: Goods available; 2: No goods "}}

Display link:

{name:‘warename‘, index:‘warename‘, width:300,sortable:false, formatter:‘showlink‘, formatoptions:{baseLinkUrl:‘query.action‘, addParam: ‘&action=edit‘}},

 

 

4. Common methods (methods)

Http://www.trirand.com/jqgridwiki/doku.php? Id = wiki: Methods

Jqgrid supports two methods to call functions:

jQuery("#grid_id").jqGridMethod( parameter1,...parameterN ); jQuery("#grid_id").jqGrid(‘method‘, parameter1,...parameterN );

The following is a new API. We recommend that you use a new calling method and also support chained calling, for example:

jQuery("#grid_id").jqGrid(‘setGridParam‘,{...}).jqGrid(‘hideCol‘,"somecol").trigger("reloadGrid");

 

1. Added {rowid, Data, position (first, before, last, after )}

$("#jqGrid_id").jqGrid("addRowData", "1" ,{‘name‘:‘zhangsan‘, ‘age‘: 20}, "first" );

2. Clear the grid

$("#jqGrid_id").jqGrid("clearGridData");  

3. returns the number of the current grid.

$("#jqGrid_id").jqGrid(‘getDataIDs‘);

4. Get the value of the current row based on rowid

$("#jqGrid_id").jqGrid(‘getRowData‘, rowIds[i]);

5. Set a row Value

$("#jqGrid_id").jqGrid(‘setRowData‘, rowIds[i], {});

For example, you need to traverse the data in the grid cyclically to obtain, set, and change the data.

VaR rowids = $ ("# jqgrid_id "). jqgrid ('getdataids '); If (rowids) {for (VAR I = 0, j = rowids. length; I <j; I ++) {var currowdata = $ ("# jqgrid_id "). jqgrid ('getrowdata', rowids [I]); // currowdata = {"name1": "value1", "name2": "value2", "name3 ": "value3 "...} if (currowdata ['name1'] = "") {// dosomething} // change: Change the name1 value $. extend (currowdata, {"name1": "newvalue1"}) $ ("# jqgrid_id "). jqgrid ('setrowdata', rowids [I], currowdata );}}

 

6. Obtain the grid parameters.

Name indicates grid options: http://www.trirand.com/jqgridwiki/doku.php? Id = wiki: Options

$("#jqGrid_id").jqGrid(‘getGridParam‘,‘name‘); 

7. Set the grid parameter, which corresponds to the preceding method.

$("#jqGrid_id").jqGrid(‘setGridParam‘, ‘name‘);

The following common parameters are required:

# Obtain the total number of records $ ("# jqgrid_id "). jqgrid ('getgridparam', 'records '); # obtain the request parameter $ ("# jqgrid_id "). jqgrid ('getgridparam', 'postdata'); # obtain the selected row and return string $ ("# jqgrid_id "). jqgrid ("getgridparam", "selrow"); # obtain multiple selected rows and return array $ ("# jqgrid_id "). jqgrid ("getgridparam", "selarrrow ");

Example: Add new request parameters to the current default request

var postData = $("#jqGrid_id").jqGrid(‘getGridParam‘,‘postData‘); $.extend(postData , {"name1":"newValue1"}) $("#jqGrid_id").jqGrid("setGridParam", {datatype: "json" }).trigger("reloadGrid", [{page:1}]);

In addition, in actual use cases, we may need to select the form value for query:

$("#queryBtn").bind("click", function() { var sdata = { "ware.warename" : $("#warenameId").val(), "ware.number" : $("#numberId").val(), "ware.valid" : $("#validId").val() }; var postData = $("#jqGridId").jqGrid("getGridParam", "postData"); $.extend(postData, sdata); $("#jqGridId").jqGrid("setGridParam", {search: true}).trigger("reloadGrid", [{page:1}]); });

 

8. Delete

$ ("# Jqgrid_id"). jqgrid ("delrowdata", rowid); // delete at the front end

When you use the preceding API to batch delete a row, the specified row is deleted based on the rowid, but the rowid changes during the deletion process, if the following method is used to delete a row, some rows cannot be deleted:

VaR GR = $ ("# jqgrid_id "). jqgrid ("getgridparam", "selarrrow"); // Delete the selected warehouse picking ticket for (VAR I = 0, j = gr. length; I <j; I ++) {$ ("# using grid_id "). jqgrid ('delrowdata', GR [I]);}

Find a solution on the Internet:

VaR GR = $ ("# jqgrid_id "). jqgrid ("getgridparam", "selarrrow"); // Delete the selected warehouse picking ticket for (VAR I = 0, j = gr. length; I <j; I ++) {$ ("# using grid_id "). jqgrid ('delrowdata', GR [0]);}

The preceding API is the frontend deletion API that deletes the frontend and backend interactions:

$("#jqGrid_id").jqGrid("delGridRow", rowid);

The following is an example of deletion:

$ ("# Removebtn "). BIND ("click", function () {var GR = $ ("# jqgridid "). jqgrid ('getgridparam', 'selrow'); If (GR) {var rowdata = $ ("# jqgridid "). jqgrid ("getrowdata", GR); $ ("# jqgridid "). jqgrid ('delgridrow', GR, {top: 100, left: 400, reloadaftersubmit: false, modal: True, // modal window URL: s2web. appurl + "JQ/Del. action ", // override editurljqmodal: True, beforesubmit: function (postdata, formid) {// id = value1, value2 ,... vaR editdata = {"Ware. ID ": rowdata. id}; postdata = $. extend (postdata, editdata); console. log (postdata); return [true, "success"] ;}, aftersubmit: function (xhr, postdata) {// return [success, message, new_id] Console. log (postdata); If (xhr. responsetext = "\" 1 \ "") {// alert ("saved successfully"); return [true, "saved successfully", postdata. id]; // message is ignored if success is true} return [false, "failed to save", postdata. id] ;}}) ;}else {alert ("select the data to delete ");}});

 

5. Events)

As the event attributes of jqgrid, it is used to listen to corresponding events, such as when selecting rows, loading, and multiple selections are triggered. API see http://www.trirand.com/jqgridwiki/doku.php? Id = wiki: events. The execution sequence of associated events is also described here:

Below is the execution order of the events when a ajax request is made 1、beforeRequest 2、loadBeforeSend 3、serializeGridData 4、loadError (if a error from the request occur - the event from steps 5 till 7 do not execute. If there is no error the event 4. does not execute and we continue to with the step 5.) 5、beforeProcessing 6、gridComplete 7、loadComplete

The following example shows the onselectrow and gridcomplete events that are concerned during development. The following functions are completed: obtain the data of the current row in the selected row and view the data in some way, when the list is loaded, calculate the total values of a column of each row in the list:

// Set the multiselect checkbox's value and set the total number of weighed items. gridcomplete: function () {var rowids =$ ("# wmsjqcontenttableid "). jqgrid ('getdataids '); var totalweight = 0, totalnumber = 0; For (VAR I = 0, j = rowids. length; I <j; I ++) {var currowdata = $ ("# wmsjqcontenttableid "). jqgrid ('getrowdata', rowids [I]); var curchk = $ ("#" + rowids [I] + ""). find (": checkbox"); curchk. ATTR ('name', 'wmscheckboxname'); curchk. ATTR ('value', Currowdata ['outstockcode']); If (currowdata ['weight']! = "") {Totalweight + = parsefloat (currowdata ['weight']);} If (currowdata ['number']! = "") {Totalnumber + = parsefloat (currowdata ['number']); }}$ ("# totalweighid "). val (totalweight); $ ("# totalpacknumid "). val (totalnumber) ;}, // update the weight, number of parts, and warehouse picking order onselectrow: function (IDS) {var rowdata =$ ("# wmsjqcontenttableid") during row selection "). jqgrid ("getrowdata", IDS); $ ("# curweighid "). val (rowdata ['weight']); $ ("# packnumid "). val (rowdata ['number']); $ ("# curwmsoutstockcodeid "). val (rowdata ['outstockcode']);}

In the following scenario, the Operation column in the last column of the List is usually required to provide operations such as deletion and modification. You can also use the gridcomplete event:

Colnames: ['item number', 'item name', 'unit price', 'purchase date', 'stocks', 'status', 'operation'], // The header has a column with a null placeholder in colmodel. Note that the index should not be repeated with the JSON {Name: 'act ', index: 'act', width: 150}

In the gridcomplete event:

Gridcomplete: function () {var IDs = $ ("# jqgridid "). jqgrid ('getdataids '); For (VAR I = 0, j = IDs. length; I <j; I ++) {var Cl = IDs [I]; Be = "<input style = 'height: 22px; width: 40px; 'Type = 'button 'value = 'edit' onclick = \ "$ ('# jqgridid '). editrow ('"+ Cl +"'); \ "/>"; // Se = "<input style = 'height: 22px; width: 40px; 'Type = 'button 'value = 'Save 'onclick = \ "$ ('# jqgridid '). saverow ('"+ Cl +"'); \ "/>"; Se = "<input style = 'height: 22px; width: 40px; 'Type = 'button 'value = 'Save 'onclick = \ "msmsaverow ('" + Cl + "'); \"/> "; ce = "<input style = 'height: 22px; width: 40px; 'Type = 'button 'value = 'cancel 'onclick = \" $ (' # jqgridid '). restorerow ('"+ Cl +"'); \ "/>"; $ ("# jqgridid "). jqgrid ('setrowdata', IDS [I], {Act: Be + Se + Ce });}},

 

6. Others

Freeze rows and columns

Jqgrid provides freeze for column, header, and column with group headers,

You need to set two items:

Frozen in colmodel: True $ ("# grid"). jqgrid ('setfrozencolumns ');

However, jqgrid's support for freeze is not so powerful. It can only be frozen from left to right. If a cell is not set in the middle, the cell after the row does not work even if it is set.

Use restrictions are listed in the official DOC:

The following limitations tell you when frozen columns can not be set-upWhen TreeGrid is enabledWhen SubGrid is enabledWhen cellEdit is enabledWhen inline edit is used - the frozen columns can not be edit.When sortable columns are enabled - grid parameter sortable is set to true or is functionWhen scroll is set to true or 1When Data grouping is enabled

Dynamic Change settings: Of course, IDS and names are all elements from left to right.

 $("#changeBtn").bind("click", function() {    $("#jqGridId").jqGrid(‘destroyFrozenColumns‘).jqGrid(‘setColProp‘,‘id‘, {frozen:true}).jqGrid(‘setColProp‘,‘name‘, {frozen:true}).jqGrid(‘setFrozenColumns‘).trigger(‘reloadGrid‘, [{current:true}]);}); 

 

 

7. refer to the following articles.

DOC:
Http://www.trirand.com/jqgridwiki/doku.php? Id = wiki: jqgriddocs
Options:
Http://www.trirand.com/jqgridwiki/doku.php? Id = wiki: Options
Colmodel_options:
Http://www.trirand.com/jqgridwiki/doku.php? Id = wiki: colmodel_options
Method
Http://www.trirand.com/jqgridwiki/doku.php? Id = wiki: Methods
Event
Http://www.trirand.com/jqgridwiki/doku.php? Id = wiki: Events

Others

Http://blog.csdn.net/gengv/article/category/648499

Http://www.trirand.com/jqgridwiki/doku.php

Http://trirand.com/blog/jqgrid/jqgrid.html

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

 

[Go] Introduction to jqgrid

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.