最近在做项目的时候,需要用到jqGrid中的一些属性和方法,在网上搜索了一下,然后顺便做一下总结
我想要实现的效果是:自动隐藏null列
在前端js中,需要做的事情的总体思路是:首先你需要获得一个model对象(它是一个对象数组,每一个对象就是一个列的集合,然后又许多列,合并为数组)
然后根据获得的model,在逐步的得到其中的数值,双层for循环
第一层:得到每一列的集合对象
第二层:得到当前列的每一个对象cell,然后判断其是否为null
下面就写一下,我在网上搜的一些相关的帖子和博文吧
①:
jqgrid获取Column属性,其实有其内置的方法的。通过
var columnArray = $(“#gridTable”).jqGrid(‘getGridParam’,'colModel’);
获取到的是一个对象数组,也就是每一个gridColumn,可以通过
columnArray[i].name获取name属性的值,也可以通过columnArray[i].index获取index属性的值。
另外可以通过var columnNames = $(“#gridTable”).jqGrid(‘getGridParam’,'colNames’); 获取title属性的值,这是个字符串数组。
columnNames[i]便可得到其值。
②:
最近做的一个项目用到了jqGrid,但总是感觉对它一知半解,于是楼主花了一些时间查看了他的API。
jqGrid中一些方法的使用说明如下:
1、获取单个选中行的行ID
var rowid = jQuery("#listTable").jqGrid("getGridParam", "selrow");
2、获取多个选中行的id
var ids=jQuery("#listTable").jqGrid('getGridParam','selarrrow');
3、获得所有行的ID数组
var ids = jQuery("#listTable").jqGrid('getDataIDs');
4、获取单个行数据
var rowData = jQuery("#listTable").jqGrid('getRowData',rowId);
其中,rowId是想要获取行数据的行ID。rowData 是包含整行数据的对象。例如,你想获得该行数据中的ID,可以直接用rowData.id来获得
5、设定行选中
//设定选中行,可设定多行选中:
jQuery("#listTable").jqGrid('setSelection',id1);
jQuery("#listTable").jqGrid('setSelection',id2);
然而,以上这些并不能够满足楼主的需求,楼主需要的是在表格加载完时,就能选中已被标记的行。于是楼主只能自己想办法。
后来,查看文档发现有gridComplete: 这样一个方法。
gridComplete:当表格所有数据都加载完成而且其他的处理也都完成时触发此事件,排序,翻页同样也会触发此事件
setSelection:参数:rowid,onselectrow。选择或反选id = rowid指定的行。若onselectrow设置为true (缺省) 则触发onSelectRow事件,否则不触发。
multiselect: true,
multiboxonly: true,
gridComplete: function() {
var rowIds = jQuery("#listTable").jqGrid('getDataIDs');
for(var k=0; kvar curRowData = jQuery("#listTable").jqGrid('getRowData', rowIds[k]);
var curChk = $("#"+rowIds[k]+"").find(":checkbox");
curChk.attr('value', curRowData['is_locked']); //缁檆heckbox璧嬪€?
if(curRowData.is_locked == '1'){
jQuery("#listTable").(rowIds[k], false);
}
}
}
后来楼主又发现一个问题,当我们设置multiselect为true时,选择任何的单元格,都会选中该行。而楼主只想在点击指定单元格时才选中行,这该怎么办呢?
beforeSelectRow:参数:rowid, e 此事件发生在用户点击行,选中该行前。rowid 为行的ID,e为事件对象该事件将返回布尔值true(行被选中)或false(行未被选中)。当返回值为false时,将不触发任何事件。
beforeSelectRow:function(rowid, e){
if(e.type == 'click'){
i = $.jgrid.getCellIndex($(e.target).closest('td')[0]),
cm = jQuery("#listTable").jqGrid('getGridParam', 'colModel');
return (cm[i].name == 'cb'); //当点击的单元格的名字为cb时,才触发选择行事件
}
return false;
}
如果我们全选时只想获得自己想要的行id该怎么做呢?
onSelectAll:参数:aRowids,status。此事件发生在点击标题的复选框时发生(multiselect为true)。aRowids为选定行ID的数组(哪些行的复选框与头复选框相同)。status为头复选框的选定的布尔值,true为选中,false为未选中。
onSelectAll:function(rowid, status) {
var ids = jQuery("#listTable").jqGrid('getDataIDs');
for (var i=0; ivar cl = ids[i];
var curRowData = $ynf_list.jqGrid('getRowData', cl);
if(curRowData.status == 1 && status == true){
jQuery("#listTable").setSelection(rowIds[k], false);
}
}
var idList=jQuery("#listTable").jqGrid('getGridParam','selarrrow');//获取所有选中行的ID
});
③:
一、主要API接口getGridParam、setGridParam:
getGridParam方法:
getGridParam("url"): 获取当前的AJAX的URL
getGridParam("sortname"):排序的字段
getGridParam("sortorder"):排序的顺序
getGridParam("selrow"):得到选中行的ID
getGridParam("page"):当前的页数
getGridParam("rowNum"):当前有多少行
getGridParam("datatype"):得到当前的datatype
getGridParam("records"):得到总记录数
getGridParam("selarrrow"):可以多选时,返回选中行的ID
setGridParam方法:
setGridParam({url:newvalue}):可以设置一个grid的ajax url,可配合trigger("reloadGrid")使用
setGridParam({sortname:newvalue}):设置排序的字段
setGridParam({sortorder:newvalue}):设置排序的顺序asc or desc
setGridParam({page:newvalue}):设置翻到第几页
setGridParam({rowNum:newvalue}):设置当前每页显示的行数
setGridParam({datatype:newvalue}):设置新的datatype(xml,json)
形式2:jQuery('#tableID').jqGrid('getGridParam','url'))
jQuery("#tableID").jqGrid('setGridParam',{page:2}).trigger("reloadGrid")
二、jqGrid colModel表体结构配置
name 必要的属性,具有唯一标识性,如在弹出的editform窗体中,将作为input的name属性
index 为排序用,最方便的是设为数据库字段
width 150,宽度,数值
align left,center,right
detefmt date:true
editable flase
editoptions edittype为先决条件,此为值,[]
editrules 编辑规范
edittype text,textarea,select,checkbox,password
formatoptions
formatter
hidedlg false (appear in the modal dialog)
hidden false 在加载时是否隐藏列
jsonmap 声明json的格式
key false
label 当没有设置colNames时,在列里用此代替,此项也为空时,就是name代替
resizable true,列宽可调节
search true,可搜索
sortable true,可排序
sorttype text,int,float,date,排序子段类型
xmlmap 声明xml的格式
三、一个例子[Array Data]
//
jQuery("#list4").jqGrid({
datatype: "local",
height: 250,
colNames:['Inv No','Date', 'Client', 'Amount','Tax','Total','Notes'],
colModel:[
{name:'id',index:'id', width:60, sorttype:"int"},
{name:'invdate',index:'invdate', width:90, sorttype:"date"},
{name:'name',index:'name', width:100},
{name:'amount',index:'amount', width:80, align:"right",sorttype:"float"},
{name:'tax',index:'tax', width:80, align:"right",sorttype:"float"},
{name:'total',index:'total', width:80,align:"right",sorttype:"float"},
{name:'note',index:'note', width:150, sortable:false}
],
multiselect: true,
caption: "Manipulating Array Data"
});
var mydata = [
{id:"1",invdate:"2007-10-01",name:"test",note:"note",amount:"200.00",tax:"10.00",total:"210.00"},
{id:"2",invdate:"2007-10-02",name:"test2",note:"note2",amount:"300.00",tax:"20.00",total:"320.00"},
{id:"3",invdate:"2007-09-01",name:"test3",note:"note3",amount:"400.00",tax:"30.00",total:"430.00"},
{id:"4",invdate:"2007-10-04",name:"test",note:"note",amount:"200.00",tax:"10.00",total:"210.00"},
{id:"5",invdate:"2007-10-05",name:"test2",note:"note2",amount:"300.00",tax:"20.00",total:"320.00"},
{id:"6",invdate:"2007-09-06",name:"test3",note:"note3",amount:"400.00",tax:"30.00",total:"430.00"},
{id:"7",invdate:"2007-10-04",name:"test",note:"note",amount:"200.00",tax:"10.00",total:"210.00"},
{id:"8",invdate:"2007-10-03",name:"test2",note:"note2",amount:"300.00",tax:"20.00",total:"320.00"},
{id:"9",invdate:"2007-09-01",name:"test3",note:"note3",amount:"400.00",tax:"30.00",total:"430.00"}
];
for(var i=0;i<=mydata.length;i++)
jQuery("#list4").jqGrid('addRowData',i+1,mydata[i]);
四、行操作
//获取选中行数据
jQuery("#a1").click( function(){
var id = jQuery("#list5").jqGrid('getGridParam','selrow');
if (id) {
var ret = jQuery("#list5").jqGrid('getRowData',id);
alert("id="+ret.id+" invdate="+ret.invdate+"...");
} else { alert("请选择一行!");}
});
//可以多选的时候获取选中行 该函数为自定义函数
function update(){
var selector = $("#grid-table").jqGrid("getGridParam", "selarrrow");
//checkbox单选时用‘selrow’,可以多选时用selarrrow 这得到是数组本该循环操作的,自己实现把。
if(selector.length>=1){
var traDeateId = selector+"_traDeate";
var accountTypeId = selector+"_accountType";
var proofNumberId = selector+"_proofNumber";
var traDeate =$('#'+traDeateId).val();
var accountType =$('#'+accountTypeId).val();
var proofNumber =$('#'+proofNumberId).val();
$('#grid-table').jqGrid('setRowData',selector, {traDeate:traDeate,accountType:accountType,proofNumber:proofNumber},'');
$("#grid-table").jqGrid('setSelection' ,selector,true); //反选择一行,去除勾选。
}else{
alert("请选择一条数据进行操作");
}
}
//删除
jQuery("#a2").click( function(){
var su=jQuery("#list5").jqGrid('delRowData',12);
if(su) alert("成功删除第12行"); else alert("删除失败");
});
//更新
jQuery("#a3").click( function(){
var su=jQuery("#list5").jqGrid('setRowData',11,{amount:"333.00",tax:"33.00",total:"366.00",note:""});
if(su) alert("更新成功"); else alert("更新失败");
});
//新增
jQuery("#a4").click( function(){
var datarow = {id:"99",invdate:"2007-09-01",name:"test3",note:"note3",amount:"400.00",tax:"30.00",total:"430.00"};
var su=jQuery("#list5").jqGrid('addRowData',99,datarow);
if(su) alert("新增成功"); else alert("新增失败");
});
五、进阶
"list9">
"pager9">
"javascript:void(0)" id="m1">Get Selected id's
"javascript:void(0)" id="m1s">Select(Unselect) row 13
jQuery("#list9").jqGrid({
url:'server.php?q=2&nd='+new Date().getTime(),
datatype: "json",
colNames:['Inv No','Date', 'Client', 'Amount','Tax','Total','Notes'],
colModel:[
{name:'id',index:'id', width:55},
{name:'invdate',index:'invdate', width:90},
{name:'name',index:'name', width:100},
{name:'amount',index:'amount', width:80, align:"right"},
{name:'tax',index:'tax', width:80, align:"right"},
{name:'total',index:'total', width:80,align:"right"},
{name:'note',index:'note', width:150, sortable:false}
],
rowNum:10,
rowList:[10,20,30],
pager: '#pager9',
sortname: 'id',
recordpos: 'left',
viewrecords: true,
sortorder: "desc",
multiselect: true,
caption: "Multi Select Example"
});
jQuery("#list9").jqGrid('navGrid','#pager9',{add:false,del:false,edit:false,position:'right'});
jQuery("#m1").click( function() {
var s;
s = jQuery("#list9").jqGrid('getGridParam','selarrrow');
alert(s);
});
jQuery("#m1s").click( function() {
jQuery("#list9").jqGrid('setSelection',"13");
});
主从表:
Invoice Header
"list10">
"pager10">
Invoice Detail
"list10_d">
"pager10_d">
"javascript:void(0)" id="ms1">Get Selected id's
jQuery("#list10").jqGrid({
url:'server.php?q=2',
datatype: "json",
colNames:['Inv No','Date', 'Client', 'Amount','Tax','Total','Notes'],
colModel:[
{name:'id',index:'id', width:55},
{name:'invdate',index:'invdate', width:90},
{name:'name',index:'name', width:100},
{name:'amount',index:'amount', width:80, align:"right"},
{name:'tax',index:'tax', width:80, align:"right"},
{name:'total',index:'total', width:80,align:"right"},
{name:'note',index:'note', width:150, sortable:false}
],
rowNum:10,
rowList:[10,20,30],
pager: '#pager10',
sortname: 'id',
viewrecords: true,
sortorder: "desc",
multiselect: false,
caption: "Invoice Header",
onSelectRow: function(ids) {
if(ids == null) {
ids=0;
if(jQuery("#list10_d").jqGrid('getGridParam','records') >0 )
{
jQuery("#list10_d").jqGrid('setGridParam',{url:"subgrid.php?q=1&id="+ids,page:1});
jQuery("#list10_d").jqGrid('setCaption',"Invoice Detail: "+ids)
.trigger('reloadGrid');
}
} else {
jQuery("#list10_d").jqGrid('setGridParam',{url:"subgrid.php?q=1&id="+ids,page:1});
jQuery("#list10_d").jqGrid('setCaption',"Invoice Detail: "+ids)
.trigger('reloadGrid');
}
}
});
jQuery("#list10").jqGrid('navGrid','#pager10',{add:false,edit:false,del:false});
jQuery("#list10_d").jqGrid({
height: 100,
url:'subgrid.php?q=1&id=0',
datatype: "json",
colNames:['No','Item', 'Qty', 'Unit','Line Total'],
colModel:[
{name:'num',index:'num', width:55},
{name:'item',index:'item', width:180},
{name:'qty',index:'qty', width:80, align:"right"},
{name:'unit',index:'unit', width:80, align:"right"},
{name:'linetotal',index:'linetotal', width:80,align:"right", sortable:false, search:false}
],
rowNum:5,
rowList:[5,10,20],
pager: '#pager10_d',
sortname: 'item',
viewrecords: true,
sortorder: "asc",
multiselect: true,
caption:"Invoice Detail"
}).navGrid('#pager10_d',{add:false,edit:false,del:false});
jQuery("#ms1").click( function() {
var s;
s = jQuery("#list10_d").jqGrid('getGridParam','selarrrow');
alert(s);
});
可展开的下级表:
<<table id="list11">table>
"pager11">
jQuery("#list11").jqGrid({
url:'server.php?q=1',
datatype: "xml",
height: 200,
colNames:['Inv No','Date', 'Client', 'Amount','Tax','Total','Notes'],
colModel:[
{name:'id',index:'id', width:55},
{name:'invdate',index:'invdate', width:90},
{name:'name',index:'name', width:100},
{name:'amount',index:'amount', width:80, align:"right"},
{name:'tax',index:'tax', width:80, align:"right"},
{name:'total',index:'total', width:80,align:"right"},
{name:'note',index:'note', width:150, sortable:false}
],
rowNum:10,
rowList:[10,20,30],
pager: '#pager11',
sortname: 'id',
viewrecords: true,
sortorder: "desc",
multiselect: false,
subGrid : true,
subGridUrl: 'subgrid.php?q=2',
subGridModel: [{ name : ['No','Item','Qty','Unit','Line Total'],
width : [55,200,80,80,80] }
],
caption: "Subgrid Example"
});
jQuery("#list11").jqGrid('navGrid','#pager11',{add:false,edit:false,del:false});
可展开的下级表二:
"listsg11">
"pagersg11">
Java Scrpt code
jQuery("#listsg11").jqGrid({
url:'server.php?q=1',
datatype: "xml",
height: 190,
colNames:['Inv No','Date', 'Client', 'Amount','Tax','Total','Notes'],
colModel:[
{name:'id',index:'id', width:55},
{name:'invdate',index:'invdate', width:90},
{name:'name',index:'name', width:100},
{name:'amount',index:'amount', width:80, align:"right"},
{name:'tax',index:'tax', width:80, align:"right"},
{name:'total',index:'total', width:80,align:"right"},
{name:'note',index:'note', width:150, sortable:false}
],
rowNum:8,
rowList:[8,10,20,30],
pager: '#pagersg11',
sortname: 'id',
viewrecords: true,
sortorder: "desc",
multiselect: false,
subGrid: true,
caption: "Grid as Subgrid",
subGridRowExpanded: function(subgrid_id, row_id) {
// we pass two parameters
// subgrid_id is a id of the div tag created whitin a table data
// the id of this elemenet is a combination of the "sg_" + id of the row
// the row_id is the id of the row
// If we wan to pass additinal parameters to the url we can use
// a method getRowData(row_id) - which returns associative array in type name-value
// here we can easy construct the flowing
var subgrid_table_id, pager_id;
subgrid_table_id = subgrid_id+"_t";
pager_id = "p_"+subgrid_table_id;
$("#"+subgrid_id).html("
");
jQuery("#"+subgrid_table_id).jqGrid({
url:"subgrid.php?q=2&id="+row_id,
datatype: "xml",
colNames: ['No','Item','Qty','Unit','Line Total'],
colModel: [
{name:"num",index:"num",width:80,key:true},
{name:"item",index:"item",width:130},
{name:"qty",index:"qty",width:70,align:"right"},
{name:"unit",index:"unit",width:70,align:"right"},
{name:"total",index:"total",width:70,align:"right",sortable:false}
],
rowNum:20,
pager: pager_id,
sortname: 'num',
sortorder: "asc",
height: '100%'
});
jQuery("#"+subgrid_table_id).jqGrid('navGrid',"#"+pager_id,{edit:false,add:false,del:false})
},
subGridRowColapsed: function(subgrid_id, row_id) {
// this function is called before removing the data
//var subgrid_table_id;
//subgrid_table_id = subgrid_id+"_t";
//jQuery("#"+subgrid_table_id).remove();
}
});
jQuery("#listsg11").jqGrid('navGrid','#pagersg11',{add:false,edit:false,del:false});
调整大小:
<table id="list12">table>
"pager12">
jQuery("#list12").jqGrid({
url:'server.php?q=2',
datatype: "json",
colNames:['Inv No','Date', 'Client', 'Amount','Tax','Total','Notes'],
colModel:[
{name:'id',index:'id', width:55},
{name:'invdate',index:'invdate', width:90},
{name:'name',index:'name', width:100},
{name:'amount',index:'amount', width:80, align:"right"},
{name:'tax',index:'tax', width:80, align:"right"},
{name:'total',index:'total', width:80,align:"right"},
{name:'note',index:'note', width:150, sortable:false}
],
rowNum:10,
rowList:[10,20,30],
pager: '#pager12',
sortname: 'id',
viewrecords: true,
sortorder: "desc",
multiselect: false,
width: 500,
height: "100%",
caption: "Auto height example"
});
jQuery("#list12").jqGrid('navGrid','#pager12',{add:false,edit:false,del:false});
搜索功能:
class="h">Search By:
type="checkbox" id="autosearch" onclick="enableAutosubmit(this.checked)"> Enable Autosearch
Code
type="text" id="search_cd" onkeydown="doSearch(arguments[0]||event)" />
Name
type="text" id="item" onkeydown="doSearch(arguments[0]||event)" />
"bigset">
"pagerb">
Java Scrpt code
jQuery("#bigset").jqGrid({
url:'bigset.php',
datatype: "json",
height: 255,
colNames:['Index','Name', 'Code'],
colModel:[
{name:'item_id',index:'item_id', width:65},
{name:'item',index:'item', width:150},
{name:'item_cd',index:'item_cd', width:100}
],
rowNum:12,
// rowList:[10,20,30],
mtype: "POST",
pager: jQuery('#pagerb'),
pgbuttons: false,
pgtext: false,
pginput:false,
sortname: 'item_id',
viewrecords: true,
sortorder: "asc"
});
var timeoutHnd;
var flAuto = false;
function doSearch(ev){
if(!flAuto)
return;
// var elem = ev.target||ev.srcElement;
if(timeoutHnd)
clearTimeout(timeoutHnd)
timeoutHnd = setTimeout(gridReload,500)
}
function gridReload(){
var nm_mask = jQuery("#item_nm").val();
var cd_mask = jQuery("#search_cd").val();
jQuery("#bigset").jqGrid('setGridParam',{url:"bigset.php?nm_mask="+nm_mask+"&cd_mask="+cd_mask,page:1}).trigger("reloadGrid");
}
function enableAutosubmit(state){
flAuto = state;
jQuery("#submitButton").attr("disabled",state);
}
六、行编辑
基本例子:
<table id="rowed1">table>
"prowed1">
type="BUTTON" id="ed1" value="Edit row 13" />
type="BUTTON" id="sved1" disabled='true' value="Save row 13" />
type="BUTTON" id="cned1" disabled='true' value="Cancel Save" />
jQuery("#rowed1").jqGrid({
url:'server.php?q=2',
datatype: "json",
colNames:['Inv No','Date', 'Client', 'Amount','Tax','Total','Notes'],
colModel:[
{name:'id',index:'id', width:55},
{name:'invdate',index:'invdate', width:90, editable:true},
{name:'name',index:'name', width:100,editable:true},
{name:'amount',index:'amount', width:80, align:"right",editable:true},
{name:'tax',index:'tax', width:80, align:"right",editable:true},
{name:'total',index:'total', width:80,align:"right",editable:true},
{name:'note',index:'note', width:150, sortable:false,editable:true}
],
rowNum:10,
rowList:[10,20,30],
pager: '#prowed1',
sortname: 'id',
viewrecords: true,
sortorder: "desc",
editurl: "server.php",
caption: "Basic Example"
});
jQuery("#rowed1").jqGrid('navGrid',"#prowed1",{edit:false,add:false,del:false});
jQuery("#ed1").click( function() {
jQuery("#rowed1").jqGrid('editRow',"13");
this.disabled = 'true';
jQuery("#sved1,#cned1").attr("disabled",false);
});
jQuery("#sved1").click( function() {
jQuery("#rowed1").jqGrid('saveRow',"13");
jQuery("#sved1,#cned1").attr("disabled",true);
jQuery("#ed1").attr("disabled",false);
});
jQuery("#cned1").click( function() {
jQuery("#rowed1").jqGrid('restoreRow',"13");
jQuery("#sved1,#cned1").attr("disabled",true);
jQuery("#ed1").attr("disabled",false);
});
客户端编辑:
<table id="rowed2">table>
"prowed2">
jQuery("#rowed2").jqGrid({
url:'server.php?q=3',
datatype: "json",
colNames:['Actions','Inv No','Date', 'Client', 'Amount','Tax','Total','Notes'],
colModel:[
{name:'act',index:'act', width:75,sortable:false},
{name:'id',index:'id', width:55},
{name:'invdate',index:'invdate', width:90, editable:true},
{name:'name',index:'name', width:100,editable:true},
{name:'amount',index:'amount', width:80, align:"right",editable:true},
{name:'tax',index:'tax', width:80, align:"right",editable:true},
{name:'total',index:'total', width:80,align:"right",editable:true},
{name:'note',index:'note', width:150, sortable:false,editable:true}
],
rowNum:10,
rowList:[10,20,30],
pager: '#prowed2',
sortname: 'id',
viewrecords: true,
sortorder: "desc",
gridComplete: function(){
var ids = jQuery("#rowed2").jqGrid('getDataIDs');
for(var i=0;i < ids.length;i++){
var cl = ids[i];
be = "+cl+"');\" />";
se = "+cl+"');\" />";
ce = "+cl+"');\" />";
jQuery("#rowed2").jqGrid('setRowData',ids[i],{act:be+se+ce});
}
},
editurl: "server.php",
caption:"Custom edit "
});
jQuery("#rowed2").jqGrid('navGrid',"#prowed2",{edit:false,add:false,del:false});
使用事件:
<table id="rowed3">table>
"prowed3">
var lastsel;
jQuery("#rowed3").jqGrid({
url:'server.php?q=2',
datatype: "json",
colNames:['Inv No','Date', 'Client', 'Amount','Tax','Total','Notes'],
colModel:[
{name:'id',index:'id', width:55},
{name:'invdate',index:'invdate', width:90, editable:true},
{name:'name',index:'name', width:100,editable:true},
{name:'amount',index:'amount', width:80, align:"right",editable:true},
{name:'tax',index:'tax', width:80, align:"right",editable:true},
{name:'total',index:'total', width:80,align:"right",editable:true},
{name:'note',index:'note', width:150, sortable:false,editable:true}
],
rowNum:10,
rowList:[10,20,30],
pager: '#prowed3',
sortname: 'id',
viewrecords: true,
sortorder: "desc",
onSelectRow: function(id){
if(id && id!==lastsel){
jQuery('#rowed3').jqGrid('restoreRow',lastsel);
jQuery('#rowed3').jqGrid('editRow',id,true);
lastsel=id;
}
},
editurl: "server.php",
caption: "Using events example"
});
jQuery("#rowed3").jqGrid('navGrid',"#prowed3",{edit:false,add:false,del:false});
完全控制:
<table id="rowed4">table>
"prowed4">
type="BUTTON" id="ed4" value="Edit row 13" />
type="BUTTON" id="sved4" disabled='true' value="Save row 13" />
jQuery("#rowed4").jqGrid({
url:'server.php?q=2',
datatype: "json",
colNames:['Inv No','Date', 'Client', 'Amount','Tax','Total','Notes'],
colModel:[
{name:'id',index:'id', width:55},
{name:'invdate',index:'invdate', width:90, editable:true},
{name:'name',index:'name', width:100,editable:true},
{name:'amount',index:'amount', width:80, align:"right",editable:true},
{name:'tax',index:'tax', width:80, align:"right",editable:true},
{name:'total',index:'total', width:80,align:"right",editable:true},
{name:'note',index:'note', width:150, sortable:false,editable:true}
],
rowNum:10,
rowList:[10,20,30],
pager: '#prowed4',
sortname: 'id',
viewrecords: true,
sortorder: "desc",
editurl: "server.php",
caption: "Full control"
});
jQuery("#ed4").click( function() {
jQuery("#rowed4").jqGrid('editRow',"13");
this.disabled = 'true';
jQuery("#sved4").attr("disabled",false);
});
jQuery("#sved4").click( function() {
jQuery("#rowed4").jqGrid('saveRow',"13", checksave);
jQuery("#sved4").attr("disabled",true);
jQuery("#ed4").attr("disabled",false);
});
function checksave(result) {
if (result.responseText=="") {alert("Update is missing!"); return false;}
return true;
}
输入类型:
"rowed5">
var lastsel2
jQuery("#rowed5").jqGrid({
datatype: "local",
height: 250,
colNames:['ID Number','Name', 'Stock', 'Ship via','Notes'],
colModel:[
{name:'id',index:'id', width:90, sorttype:"int", editable: true},
{name:'name',index:'name', width:150,editable: true,editoptions:{size:"20",maxlength:"30"}},
{name:'stock',index:'stock', width:60, editable: true,edittype:"checkbox",editoptions: {value:"Yes:No"}},
{name:'ship',index:'ship', width:90, editable: true,edittype:"select",editoptions:{value:"FE:FedEx;IN:InTime;TN:TNT;AR:ARAMEX"}},
{name:'note',index:'note', width:200, sortable:false,editable: true,edittype:"textarea", editoptions:{rows:"2",cols:"10"}}
],
onSelectRow: function(id){
if(id && id!==lastsel2){
jQuery('#rowed5').jqGrid('restoreRow',lastsel2);
jQuery('#rowed5').jqGrid('editRow',id,true);
lastsel2=id;
}
},
editurl: "server.php",
caption: "Input Types"
});
var mydata2 = [
{id:"12345",name:"Desktop Computer",note:"note",stock:"Yes",ship:"FedEx"},
{id:"23456",name:"Laptop",note:"Long text ",stock:"Yes",ship:"InTime"},
{id:"34567",name:"LCD Monitor",note:"note3",stock:"Yes",ship:"TNT"},
{id:"45678",name:"Speakers",note:"note",stock:"No",ship:"ARAMEX"},
{id:"56789",name:"Laser Printer",note:"note2",stock:"Yes",ship:"FedEx"},
{id:"67890",name:"Play Station",note:"note3",stock:"No", ship:"FedEx"},
{id:"76543",name:"Mobile Telephone",note:"note",stock:"Yes",ship:"ARAMEX"},
{id:"87654",name:"Server",note:"note2",stock:"Yes",ship:"TNT"},
{id:"98765",name:"Matrix Printer",note:"note3",stock:"No", ship:"FedEx"}
];
for(var i=0;i < mydata2.length;i++)
jQuery("#rowed5").jqGrid('addRowData',mydata2[i].id,mydata2[i]);
④:
jqgrid添加行有两种方式一种是通过获取jqgrid的colModel属性直接添加行;另外一种是自己拼接一个类似colModel的数组,通过addRowdata的方式添加到jqgrid里面。
第一种实现方法:
[javascript]
view plain
copy
- function addRowData(tableId){ //创建一条空的记录,待编辑
- var tableObject = $('#'+tableId);
- //获取表格的初始model
- var colModel = tableObject.jqGrid().getGridParam("colModel") ;
- var newRow = JSON.stringify(colModel);
- var ids = tableObject.jqGrid('getDataIDs');
- //如果jqgrid中没有数据 定义行号为1 ,否则取当前最大行号+1
- var rowid = (ids.length ==0 ? 1: Math.max.apply(Math,ids)+1);
- //获得新添加行的行号(为什么是负数呢,与编辑行差别对待)
- var newrowid = (0-rowid);
- //设置grid单元格不可编辑 (防止在添加时,用户修改其他非添加行的数据)
- tableObject.setGridParam({cellEdit:false});
- //将新行追加到表格头部
- tableObject.jqGrid("addRowData", newrowid,newRow,"first");
- //设置grid单元格可编辑(防止追加行后,可编辑列无法编辑)
- tableObject.jqGrid('editRow', newrowid, false);
- }
第二种非常复杂就不在列举了⑤:
1、获取值
1、获取单个id
获取行号,有这种方式:
var rowid = $("#grid-table").jqGrid("getGridParam", "selrow");
但是经过实际验证,这种方式不可行,当选中行,再点击同一行会出现获取不到行号的情况。
最后先在js最外部定义一个变量selId,然后使用如下代码在选中行时赋值:
onSelectRow: function (rowid, status) {
selId = rowid; //给最外层的selId赋值
}
2、获取多个选中行的id
var ids=$('#gridTable').jqGrid('getGridParam','selarrrow');
其输出格式是逗号分隔的id,如:
1,2,3,4,5
3、获得所有行的ID数组
var ids = $("jqgridtableid").jqGrid('getDataIDs');
4、获取行数据
如果想获取选择的行的数据,只要传入rowId即可,如下:
var rowData = $('#gridTable').jqGrid('getRowData',rowId);
而这个rowData是一个对象,如果要获取选择的行的这个对象的属性值,如name的值,需如下:
var Name= rowData.name;
5、获取单元格数据
var celldata = $("jqgridtableid").jqGrid('getCell',id,colnum);
6、设定行选中
//设定选中行,可设定多行选中:
$("jqgridtableid").jqGrid('setSelection',id1);
$("jqgridtableid").jqGrid('setSelection',id2);
2、自定义分页、数据交互
何谓自定义?就是允许你用你自己喜欢的js对象与后端做数据交互。如jsonReader。
如果这个地方的Id设置错了,那么jqGrid就会自动以行号作为Id,这样会影响删除的。如果根据Id来删,很有可能删错行。
jsonReader: {
id: "Id", //相当于设置主键
root: "JsonArray", //Json数据
total: "TotalPage", //总页数
page: "CurrentPage", //当前页
records: "TotalRecord",//总记录数
repeatitems: false
},
这样一来,对于数据表格,在C#中,我可以用一个泛型类,就能够与jqGrid表格进行交互(其中,包括了分页信息,数据内容)。
///
/// 分页ViewModel
///
public class jQGrid where T : class
{
public jQGrid()
{ }
///
/// 带4个参数的构造函数
///
/// 每页显示行数
/// 当前页
/// 结果总记录数
/// JSON数据
public jQGrid(int rows, int currentPage, int totalRecord, IList jsonArray)
{
TotalPage = this.CalculateTotalPage(rows, totalRecord);
CurrentPage = currentPage;
TotalRecord = totalRecord;
JsonArray = jsonArray;
}
public int TotalPage { get; set; }
public int CurrentPage { get; set; }
public int TotalRecord { get; set; }
public IList JsonArray { get; set; }
///
/// 根据每页显示数与总记录数计算出总页数
///
/// 每页显示数
/// 结果总记录数
///
public int CalculateTotalPage(int rows, int totalRecord)
{
return Convert.ToInt32(Math.Ceiling((double)totalRecord / (double)rows));
}
}
3、搜索的实现
搜索的实现主要通过jqGrid的postData像服务器端传递参数。
$("#btnSearch").click(function () {
var rules = "";
$("#multipleSearchDialog").each(function (i) {
$(".div-padding :input").each(function () {
if ($(this).val()) {
rules += '"' + $(this).attr("name") + '":"' + $(this).val() + '"';
}
})
});
ParamJson = '{' + rules + '}';
var postData = $("#grid-table").jqGrid("getGridParam", "postData");
$.extend(postData, { Param: ParamJson });
$("#grid-table").jqGrid("setGridParam", { search: true }).trigger("reloadGrid", [{ page: 1}]); //重载JQGrid
});
搜索功能主要通过postData向服务器端传递数据。后端获取参数从而进行处理:
Dictionary<string, string> DicParam = new Dictionary<string, string>();
string Param = Convert.ToString(Request["Param"]);
if (!string.IsNullOrEmpty(Param))
{
System.Web.Script.Serialization.JavaScriptSerializer sr = new System.Web.Script.Serialization.JavaScriptSerializer();
DicParam = sr.Deserialize(Param, typeof(Dictionary<string, string>)) as Dictionary<string, string>;
}
这样就获取到了查询参数的键值对,至于参数怎么用,一般都是用于sql的where子句。