常见的是jqgrid单元格编辑完后就触发与服务端的交互,我在开发的时候碰到下面的需求(如下图):
在点击确定按钮前要结束最后一个单元格编辑状态,如上图,否则getRowData方法获取的表格数据包含文本编辑框的html代码,如下图
且必须用saveCell函数结束文本编辑状态,(不能用restoreCell函数,因为此函数只能获取编辑前的数据)写法如下:
$("#businessplanmag_add_list").jqGrid("saveCell",businessplanmag_iRow,businessplanmag_iCol);
businessplanmag_iRow,businessplanmag_iCol分别表示单元格的水平和垂直坐标,这是2个全局变量,在下面赋值
beforeEditCell:function(rowid,cellname,value,iRow,iCol){
businessplanmag_iRow=iRow;
businessplanmag_iCol=iCol;
},
完整代码如下:
//添加修改_公用
function businessplanmag_table_show(jsondata){
$("#businessplanmag_add_list").jqGrid("GridUnload");
$("#businessplanmag_add_list").jqGrid({
datastr:jsondata,
datatype:"jsonstring",
width:600,
height: "100%",
colNames:['ID','省区id','省id','省区','计划成交额','线上成交额','线下成交额'],
colModel:[
{name:'p_id',index:'p_id', width:80,key:true,align:'center',hidden:true},
{name:'areaid',index:'areaid', width:50,align:'center',hidden:true},
{name:'proid',index:'proid', width:50,align:'center',hidden:true},
{name:'area_name',index:'area_name', width:150,align:'center'},
{name:'business_volume_plan',index:'business_volume_plan', width:150,align:'right',editable:true,editrules:{custom:true, custom_func:function(value, colname){
if(rule.price.test(value)){ return [true];}else{ return [false,"请输入数字,可保留2位小数!"]; }
}}},
{name:'business_volume_online',index:'business_volume_online', width:150,align:'right',editable:true,editrules:{custom:true, custom_func:function(value, colname){
if(rule.price.test(value)){ return [true];}else{ return [false,"请输入数字,可保留2位小数!"]; }
}}},
{name:'business_volume_offline',index:'business_volume_offline', width:150,align:'right'}
],
jsonReader : {
repeatitems: false,
id:"p_id",
},
cellEdit:true,
cellsubmit:"clientArray",
beforeEditCell:function(rowid,cellname,value,iRow,iCol){
businessplanmag_iRow=iRow;
businessplanmag_iCol=iCol;
},
afterSaveCell:function(id,name,val,iRow,iCol){
if(name=="business_volume_plan"){
var business_volume_offline=val-$("#businessplanmag_add_list").jqGrid("getCell",id,"business_volume_online");
}else{
var business_volume_offline=$("#businessplanmag_add_list").jqGrid("getCell",id,"business_volume_plan")-val;
}
if(business_volume_offline<0){
$("#businessplanmag_add_list").jqGrid("restoreCell",iRow,iCol);
$.longhz.alert("计划成交额不能小于线上成交额!");
return;
}
$("#businessplanmag_add_list").jqGrid("setCell",id,"business_volume_offline",business_volume_offline.toFixed(2));
},
caption:""
});
}
需要注意以下几点:
1、 cellsubmit的值必须是"clientArray";
2、afterSaveCell函数在单元格编辑完后触发,实现功能如下图
3、此函数只用于呈现表格,表格数据是通过参数jsondata传入,这样做的好处是可动态更改表格的呈现数据。
4、这里用到了jqgrid编辑自带的验证方法
editrules:{custom:true, custom_func:function(value, colname){
if(rule.price.test(value)){ return [true];}else{ return [false,"请输入数字,可保留2位小数!"]; }
}}