jqGrid how to collapse row when clicking on other row - jqgrid

In a main grid, when I click on one row, it become 'highlighted' and the seven subgrids are showed.
Here is an example where first row is selected, and near to be edited (work in progress) :
Now, if I click on second row of the main grid, the first is hidden and the second selected. I click after on edit button and a warning appears : no selected row !
If I click again on the second row, it become unselected, and again I click for selecting and editing, that runs fine ! So I presume that my code for switching between collapsed and expanded status is somewhere wrong :
UPDATED 2013-04-11
Following Oleg's answer, I join the full code (limited to 30000) of my program :
jQuery(function ($) {
var resetAltRows = function () {
$(this).children("tbody:first").children('tr.jqgrow').removeClass('myAltRowClass');
$(this).children("tbody:first").children('tr.jqgrow').each(function(){
var arbo=$(this).find('td:eq(0)').text().substr(0,1);
$(this).addClass('myAltRowClass1'+arbo);
if(arbo==1)$(this).find('td:eq(1) input:checkbox').attr('checked','checked');
});
$(this).children("tbody:first").children('tr.jqgrow:visible:odd').addClass('myAltRowClass');
};
var OldSelectedRow=null,
height=$('body').height()-235,
numRows=Math.floor(height/23)-(Math.floor(height/23)%5),
heightRows=numRows*23,
myGrid = $("#tab51");
//************************
//************************
//************************
myGrid.jqGrid({
caption:"Liste des BONS DE TRAVAUX STANDARD",
hidegrid:false,
url:'opt511.php',
datatype: "json",
height:heightRows,
rowNum:numRows,
shrinkToFit:true,
colNames:['Id','A.R.C.','B.T.','Date ARC','Client','Nom','Ville','Cde client','Matériel','Marque','Prest.','Description','N° série','Objet','X','b.type','idref'],
colModel:[
{name:'b.id',index:'b.id', hidden:true,key:true},
{name:'b.arc',index:'b.arc', width:60,align:'center',editable:true},
{name:'b.ind',index:'b.ind', width:30,align:"center"},
{name:'b.date_in',index:'b.date_in', width:70,align:"center"},
{name:'c.code',index:'c.code', width:40},
{name:'c.descr',index:'c.descr',width:200},
{name:'c.ville',index:'c.ville', width:200},
{name:'b.cde_clt',index:'b.cde_clt', width:150},
{name:'q.code',index:'q.code', width:80},
{name:'k.code',index:'k.code', width:80},
{name:'b.nature',index:'b.nature', stype:'select',width:40,align:'center',
searchoptions:{
dataUrl:'sh51.php'
},
cellattr: function (rowId, val, rawObject, cm, rdata) {
return 'title="' + rawObject[15] + '"';
}
},
{name:'2m.descr',index:'2m.descr', width:200},
{name:'p.numserie',index:'p.numserie', width:80},
{name:'b.descr',index:'b.descr', width:200},
{name:'clos',index:'clos', width:20,stype:'select',align:'center',sortable:false,
searchrules:{date:true},
search:true,
searchoptions:{
value:{"": "?", 0:"En cours", 1: "Clôturé"},
defaultValue:0
}
},
{name:'btype',index:'btype', width:40,hidden:true},
{name:'idref',index:'btype', width:40,hidden:true}
],
postData: {
filters:'{"groupOp":"AND","rules":['+
'{"field":"clos","op":"eq","data":"0"}]}'
},
search:true,
pager: '#tab51p',
sortname: 'b.arc',
gridComplete:function(){
OldSelectedRow=null;
sortDataCol(this);,
},
onSelectRow:function(id,status){
alert('begin = '+myGrid.jqGrid('getGridParam','selrow'));
if(OldSelectedRow!=id){
if(OldSelectedRow!=null){
myGrid.jqGrid ('collapseSubGridRow', OldSelectedRow);
$('#'+OldSelectedRow).removeClass('ui-state-highlight');
}
$('#'+id).addClass('ui-state-highlight');
OldSelectedRow=id;
myGrid.jqGrid('expandSubGridRow',id);
}else{
myGrid.jqGrid ('collapseSubGridRow', id);
$('#'+id).removeClass('ui-state-highlight');
OldSelectedRow=null;
}
alert('end = '+myGrid.jqGrid('getGridParam','selrow'));
},
subGrid: true,
subGridRowExpanded: function(subgrid_id, row_id) {
//*********************
// 1ST SUBGRID
//*********************
var rowdata = myGrid.jqGrid('getRowData',row_id),
btr=rowdata['b.id'],
subgrid_table_id = subgrid_id+"_a",
pager_id = "p_"+subgrid_table_id;
$("#"+subgrid_id).html("<table id='"+subgrid_table_id+"' class='scroll'></table><div id='"+pager_id+"' class='scroll'></div>");
$("#"+subgrid_table_id).jqGrid({
url:"sg511a.php?id="+row_id+"&btr="+btr,
datatype: "json",
colNames: ['Nature','Information'],
colModel: [
{name:'c.code',index:'c.code', width:150,align:'right',sortable:false},
{name:'p.coeff',index:'p.coeff', width:630,sortable:false}
],
height: '100%',
autowidth:true,
caption:'1 - INFORMATIONS CLIENT',
});
//*********************
// 2ND SUBGRID
//*********************
var clt=rowdata['c.code'],
subgrid_table_id = subgrid_id+"_b",
pager_id = "p_"+subgrid_table_id;
$("#"+subgrid_id).append("<table id='"+subgrid_table_id+"' class='scroll'></table><div id='"+pager_id+"' class='scroll'></div>");
$("#"+subgrid_table_id).jqGrid({
url:"sg511b.php?id="+row_id+"&clt="+clt,
datatype: "json",
colNames: ['Id','X','Civilité','Nom','Prénom','Service'],
colModel: [
{name:'t.id',index:'t.id', width:60, align:"center",hidden:true},
{name:'check',index:'check', width:20,sortable:false,formatter:'checkbox',align:'center',
editable: false, edittype: 'checkbox', editoptions: {value: "true:false", defaultValue: "false"},
formatoptions: {disabled: false}
},
{name:'v.code',index:'v.code', width:60,sortable:false},
{name:'t.nom',index:'t.nom', width:210,sortable:false},
{name:'t.prenom',index:'t.prenom', width:210,sortable:false},
{name:'f.descr',index:'f.descr', width:220,sortable:false}
],
pager: pager_id,
sortname: 't.nom',
hiddengrid:true,
scroll:true,
maxheight: 230,
autowidth:true,
caption:'2 - PERSONNES A CONTACTER',
gridComplete:function(){
OldSelectedRow=null;
sortDataCol(this);
}
});
$("#"+subgrid_table_id).jqGrid('navGrid',"#"+pager_id,{search:false,add:false,edit:false,del:false});
//*********************
// 3TH SUBGRID
//*********************
rowdata = myGrid.jqGrid('getRowData',row_id);
var parc=rowdata['p.id'];
var subgrid_table_id, pager_id;
subgrid_table_id = subgrid_id+"_c";
pager_id = "p_"+subgrid_table_id;
$("#"+subgrid_id).append("<table id='"+subgrid_table_id+"' class='scroll'></table><div id='"+pager_id+"' class='scroll'></div>");
$("#"+subgrid_table_id).jqGrid({
url:"sg511c.php?id="+row_id+"&parc="+parc,
datatype: "json",
colNames: ['Id','Ensemble','Quantité','Article','Désignation','Matière'],
colModel: [
{name:'a.id',index:'a.id', width:60, align:"center",hidden:true},
{name:'c.code',index:'c.code', width:100},
{name:'p.coeff',index:'p.coeff', width:60,align:"center"},
{name:'a.code',index:'a.code', width:80},
{name:'a.descr',index:'a.descr',width:400},
{name:'m.code',index:'m.code', width:80}
],
pager: pager_id,
sortname: 'c.code',
sortorder: "asc",
hiddengrid:true,
rownumbers: true,
rownumWidth: 40,
gridview: true,
scroll:true,
maxheight: 230,
autowidth:true,
onSortCol: function (index, idxcol, sortorder) {
// montre la colonne sélectionnée pour le tri de la grille
if (this.p.lastsort >= 0 && this.p.lastsort !== idxcol
&& this.p.colModel[this.p.lastsort].sortable !== false) {
$(this.grid.headers[this.p.lastsort].el).find(">div.ui-jqgrid-sortable>span.s-ico").show();
$(this.grid.headers[this.p.lastsort].el).removeClass('ui-state-active');
}
$(this.grid.headers[idxcol].el).addClass('ui-state-active');
},
altRows:true,
altclass:'myAltRowClass',
viewrecords: true,
caption:'3 - SPECIFICATIONS TECHNIQUES',
emptyrecords: 'Aucune donnée correspondante...',
});
//*********************
// 4TH SUBGRID
//*********************
rowdata = myGrid.jqGrid('getRowData',row_id);
var parc=rowdata['idref'];
var subgrid_table_id, pager_id;
subgrid_table_id = subgrid_id+"_d";
pager_id = "p_"+subgrid_table_id;
$("#"+subgrid_id).append("<table id='"+subgrid_table_id+"' class='scroll'></table><div id='"+pager_id+"' class='scroll'></div>");
$("#"+subgrid_table_id).jqGrid({
url:"sg511d.php?id="+row_id+"&parc="+parc,
datatype: "json",
colNames: ['Id','Ensemble','Quantité','Article','Désignation','Matière'],
colModel: [
{name:'a.id',index:'a.id', width:60, align:"center",hidden:true},
{name:'c.code',index:'c.code', width:100},
{name:'p.coeff',index:'p.coeff', width:60,align:"center"},
{name:'a.code',index:'a.code', width:80},
{name:'a.descr',index:'a.descr',width:400},
{name:'m.code',index:'m.code', width:80}
],
pager: pager_id,
sortname: 'c.code',
sortorder: "asc",
hiddengrid:true,
rownumbers: true,
rownumWidth: 40,
gridview: true,
scroll:true,
maxheight: 230,
autowidth:true,
onSortCol: function (index, idxcol, sortorder) {
// montre la colonne sélectionnée pour le tri de la grille
if (this.p.lastsort >= 0 && this.p.lastsort !== idxcol
&& this.p.colModel[this.p.lastsort].sortable !== false) {
$(this.grid.headers[this.p.lastsort].el).find(">div.ui-jqgrid-sortable>span.s-ico").show();
$(this.grid.headers[this.p.lastsort].el).removeClass('ui-state-active');
}
$(this.grid.headers[idxcol].el).addClass('ui-state-active');
},
altRows:true,
altclass:'myAltRowClass',
viewrecords: true,
caption:'4 - PIECES A PREPARER',
emptyrecords: 'Aucune donnée correspondante...',
gridComplete:function(){
colModel = $("#"+subgrid_id+'_d').jqGrid('getGridParam', 'colModel');
sortName =$("#"+subgrid_id+'_d').jqGrid('getGridParam', 'sortname');
$('#gbox_' + $.jgrid.jqID($("#"+subgrid_id+'_d')[0].id) +
' tr.ui-jqgrid-labels th.ui-th-column').each(function (i) {
var cmi = colModel[i], colName = cmi.name;
if (cmi.sortable !== false) {
$(this).find('>div.ui-jqgrid-sortable>span.s-ico').show();
} else if (!cmi.sortable && colName !== 'rn' && colName !== 'cb' && colName !== 'subgrid') {
$(this).find('>div.ui-jqgrid-sortable').css({cursor: 'default'});
}
if (cmi.name === sortName) {
$(this).addClass('ui-state-active');
//alert(i);
var gridId = $("#"+subgrid_id+'_d').jqGrid('getDataIDs');
for (var countRow = 0; countRow < gridId .length; countRow ++)
{
var rowId = gridId [countRow ];
var dataFromTheRow = $("#"+subgrid_id+'_d').jqGrid ('getRowData', rowId);
$("#"+subgrid_id+'_d').jqGrid('setCell',rowId, i, '','ui-widget-header');
$("#"+subgrid_id+'_d').jqGrid('setCell',rowId, i, '',{'border-top':0,'border-left':0});
}
}
});
},
});
$("#"+subgrid_table_id).jqGrid('navGrid',"#"+pager_id,{search:false,add:false,edit:false,del:false});
//*********************
// 5TH SUBGRID
//*********************
rowdata = myGrid.jqGrid('getRowData',row_id);
var btr=rowdata['b.id'],lastId='';
var prest=rowdata['btype'];
var nature=rowdata['b.nature'];
var subgrid_table_id, pager_id;
subgrid_table_id = subgrid_id+"_e";
pager_id = "p_"+subgrid_table_id;
$("#"+subgrid_id).append("<table id='"+subgrid_table_id+"' class='scroll'></table><div id='"+pager_id+"' class='scroll'></div>");
$("#"+subgrid_table_id).jqGrid({
url:"sg511e.php?id="+row_id+"&btr="+btr,
datatype:"json",
mType:'POST',
loadui: "disable",
colNames:['id','Prestations','Radio','Checked','Disabled','Select','Informations'],
colModel:[
{name:'id',index:'id',width:100,hidden:true},
{name:'name',index:'name',width:550,sortable:false,
formatter: function (cellvalue,options,rowObject) {
if(rowObject.radio.length==0){
if(rowObject.id.substr(0,1)=='1'){
var check="checked='checked'";
}else{
var check='';
}
if(rowObject.disabled>'0'){
var disabled="disabled";
}else{
var disabled='';
}
var box="<input type='checkbox' class='itmchk' "+check+" "+disabled+"/>";
}else{
var box="<input type='radio' class='itmrad' id='"+rowObject.radio+"' name='"+rowObject.radio+"' "+(rowObject.checked>0?'checked':'')+" />";
}
switch(rowObject.level){
case '0':
var bstyle="<strong>", estyle="</strong>";
break;
case '1':
var bstyle="", estyle="";
break;
default:
var bstyle="<em>", estyle="</em>";
}
return box + bstyle + $.jgrid.htmlEncode(cellvalue) + estyle;
}
},
{name:'radio',index:'radio',width:30,sortable:false,hidden:true},
{name:'checked',index:'checked',width:30,sortable:false,hidden:true},
{name:'disabled',index:'disabled',width:30,sortable:false,hidden:true},
{name:'select',index:'select',width:200,sortable:false,hidden:true},
{name:'data',index:'data',width:230,sortable:false,
formatter: function (cellvalue,options,rowObject) {
var cell='';
if(rowObject.select>" "){
var tab=rowObject.select.split("|");
var id=rowObject.id.substr(0,1);
cell="<select class='itmsel'>";
for(var i=0;i<tab.length;i++){
var fld=tab[i].split(';');
var opt="<option value='"+fld[0]+"' class='myAltRowClass1"+id+"'";
if(i==0){
opt+=" style='font-style:italic;'";
}else{
opt+=" style='color:red;'";
}
opt+=">"+(i>0?' • ':'')+fld[1]+"</option>";
cell+=opt;
}
cell+='</select>';
}
return cell;
}
}
],
sortname: 'id',
sortorder: "asc",
hiddengrid:true,
gridview: true,
treeGrid:true,
pager:pager_id,
treeGridModel: "adjacency",
treedatatype: 'json',
ExpandColumn: 'name',
jsonReader: {
repeatitems: false,
root: function (obj) { return obj; },
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.length; }
},
scroll:true,
autowidth:true,
height: 230,
loadComplete: function() {
var grid = this;
resetAltRows.call(this);
$(this).find('tr.jqgrow td div.treeclick').click(function(){
resetAltRows.call(grid);
});
$(this).find('tr.jqgrow td span.cell-wrapper').click(function(){
resetAltRows.call(grid);
});
$("#"+subgrid_table_id).jqGrid('setLabel', 'name', '<b>'+nature+' - '+prest+'</b>');
//
},
beforeSelectRow: function (rowid, e) {
var $this = $(this),
isLeafName = $this.jqGrid("getGridParam", "treeReader").leaf_field,
localIdName = $this.jqGrid("getGridParam", "localReader").id,
localData,
state,
setCheckedStateOfChildrenItems = function (children) {
$.each(children, function () {
$("#" + this[localIdName] + " input.itmchk").prop("checked", state);
if (!this[isLeafName]) {
setCheckedStateOfChildrenItems($this.jqGrid("getNodeChildren", this));
}
});
};
if (e.target.nodeName === "INPUT" && $(e.target).hasClass("itmchk")) {
state = $(e.target).prop("checked");
localData = $this.jqGrid("getLocalRow", rowid);
setCheckedStateOfChildrenItems($this.jqGrid("getNodeChildren", localData), state);
}
},
onSortCol: function (index, idxcol, sortorder) {
// montre la colonne sélectionnée pour le tri de la grille
if (this.p.lastsort >= 0 && this.p.lastsort !== idxcol
&& this.p.colModel[this.p.lastsort].sortable !== false) {
$(this.grid.headers[this.p.lastsort].el).find(">div.ui-jqgrid-sortable>span.s-ico").show();
$(this.grid.headers[this.p.lastsort].el).removeClass('ui-state-active');
}
$(this.grid.headers[idxcol].el).addClass('ui-state-active');
},
caption:'5 - TRAVAUX A EFFECTUER',
});
$("#"+subgrid_table_id).jqGrid('navGrid',"#"+pager_id,{search:false,add:false,edit:false,del:false});
//*********************
// 6TH SUBGRID
//*********************
rowdata = myGrid.jqGrid('getRowData',row_id);
var parc=rowdata['p.id'];
var subgrid_table_id, pager_id;
subgrid_table_id = subgrid_id+"_f";
pager_id = "p_"+subgrid_table_id;
$("#"+subgrid_id).append("<table id='"+subgrid_table_id+"' class='scroll'></table><div id='"+pager_id+"' class='scroll'></div>");
$("#"+subgrid_table_id).jqGrid({
url:"sg511f.php?id="+row_id+"&parc="+parc,
datatype: "json",
colNames: ['Id','Ensemble','Quantité','Article','Désignation','Matière'],
colModel: [
{name:'a.id',index:'a.id', width:60, align:"center",hidden:true},
{name:'c.code',index:'c.code', width:100},
{name:'p.coeff',index:'p.coeff', width:60,align:"center"},
{name:'a.code',index:'a.code', width:80},
{name:'a.descr',index:'a.descr',width:400},
{name:'m.code',index:'m.code', width:80}
],
pager: pager_id,
sortname: 'c.code',
sortorder: "asc",
hiddengrid:true,
rownumbers: true,
rownumWidth: 40,
gridview: true,
scroll:true,
maxheight: 230,
autowidth:true,
onSortCol: function (index, idxcol, sortorder) {
// montre la colonne sélectionnée pour le tri de la grille
if (this.p.lastsort >= 0 && this.p.lastsort !== idxcol
&& this.p.colModel[this.p.lastsort].sortable !== false) {
$(this.grid.headers[this.p.lastsort].el).find(">div.ui-jqgrid-sortable>span.s-ico").show();
$(this.grid.headers[this.p.lastsort].el).removeClass('ui-state-active');
}
$(this.grid.headers[idxcol].el).addClass('ui-state-active');
},
altRows:true,
altclass:'myAltRowClass',
viewrecords: true,
caption:'6 - INTERVENANTS',
emptyrecords: 'Aucune donnée correspondante...',
});
$("#"+subgrid_table_id).jqGrid('navGrid',"#"+pager_id,{search:false,add:false,edit:false,del:false});
$("#"+subgrid_table_id).jqGrid('filterToolbar',{stringResult: true,searchOnEnter : false});
// montre la colonne triée au chargement des données
colModel = $("#"+subgrid_table_id).jqGrid('getGridParam', 'colModel');
sortName = $("#"+subgrid_table_id).jqGrid('getGridParam', 'sortname');
$('#gbox_' + $.jgrid.jqID($("#"+subgrid_table_id)[0].id) +
' tr.ui-jqgrid-labels th.ui-th-column').each(function (i) {
var cmi = colModel[i], colName = cmi.name;
if (cmi.sortable !== false) {
$(this).find('>div.ui-jqgrid-sortable>span.s-ico').show();
} else if (!cmi.sortable && colName !== 'rn' && colName !== 'cb' && colName !== 'subgrid') {
$(this).find('>div.ui-jqgrid-sortable').css({cursor: 'default'});
}
if (cmi.name === sortName) {
$(this).addClass('ui-state-active');
}
});
//*********************
// 7TH SUBGRID
//*********************
rowdata = myGrid.jqGrid('getRowData',row_id);
var parc=rowdata['p.id'];
var subgrid_table_id, pager_id;
subgrid_table_id = subgrid_id+"_g";
pager_id = "p_"+subgrid_table_id;
$("#"+subgrid_id).append("<table id='"+subgrid_table_id+"' class='scroll'></table><div id='"+pager_id+"' class='scroll'></div>");
$("#"+subgrid_table_id).jqGrid({
url:"sg511g.php?id="+row_id+"&parc="+parc,
datatype: "json",
colNames: ['Id','Ensemble','Quantité','Article','Désignation','Matière'],
colModel: [
{name:'a.id',index:'a.id', width:60, align:"center",hidden:true},
{name:'c.code',index:'c.code', width:100},
{name:'p.coeff',index:'p.coeff', width:60,align:"center"},
{name:'a.code',index:'a.code', width:80},
{name:'a.descr',index:'a.descr',width:400},
{name:'m.code',index:'m.code', width:80}
],
pager: pager_id,
sortname: 'c.code',
sortorder: "asc",
hiddengrid:true,
rownumbers: true,
rownumWidth: 40,
gridview: true,
scroll:true,
maxheight: 230,
autowidth:true,
onSortCol: function (index, idxcol, sortorder) {
// montre la colonne sélectionnée pour le tri de la grille
if (this.p.lastsort >= 0 && this.p.lastsort !== idxcol
&& this.p.colModel[this.p.lastsort].sortable !== false) {
$(this.grid.headers[this.p.lastsort].el).find(">div.ui-jqgrid-sortable>span.s-ico").show();
$(this.grid.headers[this.p.lastsort].el).removeClass('ui-state-active');
}
$(this.grid.headers[idxcol].el).addClass('ui-state-active');
},
altRows:true,
altclass:'myAltRowClass',
viewrecords: true,
caption:'7 - PLAN DE PREVENTION',
emptyrecords: 'Aucune donnée correspondante...',
});
$("#"+subgrid_table_id).jqGrid('navGrid',"#"+pager_id,{search:false,add:false,edit:false,del:false});
$("#"+subgrid_table_id).jqGrid('filterToolbar',{stringResult: true,searchOnEnter : false});
var subgridg="#"+subgrid_id;
// #tab_51_1;
var chaine='abcdefg';
$(".ui-jqgrid-titlebar",subgridg).click(function(){
var titlebar=this;
var clicked=chaine.indexOf($(titlebar).parent().attr('id').substr(-1));
// id is 'tab51_1_a' so clicked is 0
var depart=$(titlebar).parent().parent().parent().attr('id');
// I run my search from id 'tab51_1' class 'tablediv'
$('#'+depart).find('.ui-jqgrid-view').each(function(idx){
if(idx==clicked){
$(".ui-jqgrid-titlebar-close", titlebar).click();
}else{
if(typeof $(subgridg).find('.ui-jqgrid-bdiv:eq('+idx+')').css('display')=='undefined'||$(subgridg).find('.ui-jqgrid-bdiv:eq('+idx+')').css('display')=='block'){
$(subgridg).find(".ui-jqgrid-titlebar-close:eq("+idx+")").click();
}
}
});
});
},
subGridRowColapsed: function(subgrid_id, row_id) {
$("#"+subgrid_id+"_a").remove();
$("#"+subgrid_id+"_b").remove();
$("#"+subgrid_id+"_c").remove();
$("#"+subgrid_id+"_d").remove();
$("#"+subgrid_id+"_e").remove();
$("#"+subgrid_id+"_f").remove();
$("#"+subgrid_id+"_g").remove();
myGrid.jqGrid('resetSelection');
}
});});
where I don't use any subGridOptions so I think that false is the defaultValue of reloadOnExpand.
I have added in OnSelectedRow function 2 alerts, at beginning and ending of function.
The first click display fine selrows for begin and end, but for next click, the end alert displays 'null'.
I have tried also to delete all parts into 'subGridRowExpanded' and 'subGridRowColapsed' functions.
The trouble doesn't happen, begin and end selrows are fine and I can edit row as I want.
Inner workings of jqGrid seem very complicate for me as I'm not used to work with it, and I have to thank you one more time for all time you spend for helping noobs as me. You are always right in your comments and I hope you will be for long time on this forum.
Thanks again. Have a nice day. JiheL
UPDATED 2013-04-22
After applying all suggests from Oleg, I made some changes in the 20 scripts of my app, which all are built in the same way.
For this subject, here is the small part of onSelectRow I changed :
onSelectRow:function(id){
var expanded = $("td.sgexpanded", myGrid)[0];
if(expanded){
$(expanded).trigger("click").parent().removeClass('ui-state-highlight');
}
myGrid.jqGrid('expandSubGridRow',id);
$('#'+id).addClass('ui-state-highlight');
alert(id+' '+myGrid.jqGrid('getGridParam','selrow'));
},
but no more luck for the result, I can't edit a row which has been expanded after collapse other row. I don't understand why selrow changes after collapse old row and expand selected row.
I hope someone could drive me about this trouble, I think I'm not alone to meet this problem.
Many thanks in advance for your kind help, really appreciated. JiheL
UPDATED 2013-04-23
After applying Oleg's suggests the main problem (edit an expanded row after collapsing other) seems to be solved. But setting selected row to top of grid runs fine with five first rows, but not with following rows. Strange ! Here is a snapshot of fact :
Strange because demo in http://jsfiddle.net/jihel/JMcKF/ runs fine and has been created with my app code ! I'm searching what can be wrong or alter scrollTop, if someone has already met such a trouble and have an idea for solving, many thanks for all your help. Have a nice day

It's difficult to analyse so long code. So I post just some comments about the potential problems which I can see in the code after I looked through it.
The main problem which I see: you should use idPrefix option in all subgrids (or in the main grid and subgrid). The value of idPrefix option option should depend on rowid where the subgrid will be opened. For example you can use
idPrefix: "s_" + row_id + "_a_"
for the first subgrid, idPrefix: "s_" + row_id + "_b_" for the second subgrid and so on.
I recommend you don't use . (dot) or any other meta-characters in the column name. It's origin of potential errors in your code and in the code of jqGrid. You should understand that the name property will be used to build id attributes of some internal elements of jqGrid. There are some restrictions in CSS which characters are permitted in id attribute. Additionally jqGrid have to build selectors to get the corresponding elements from the page. For example $("#" + rowid) will be wrong selector if rowid includes . because the selector ("#a.b") will be interpreted as: element with id=a and the class b instead of id="a.b". Old versions of jqGrid don't worked at all with such ids and such names. Recent version of jqGrid should works, but nevertheless usage of meta-characters in ids increase the complexity of the code in many time. Do you really need it?
Because of almost the same problem I don't recommend you to use the same name property for different tables. It could be important if you plan to use searching filter for multiple grids or subgrids (to use filterToolbar for multiple grids). Currently you use 'c.code' for example in multiple subgrids which is potential origin of the future problems.
If you really need to use . for searching and you use datatype: "json" without loadonce: true then you can use index which has . and name which has no .. For example you can use name: 'b_id', index: 'b.id'. If you use index value which is the same as the value of name property, it's recommended to remove index property from the column definition.
Additionally I would don't recommend to use scroll:true option of jqGrid. In general virtual scrolling is nice feature, but in my opinion the implementation of virtual scrolling have many bugs abd side effects. So I recommend don't use it. If you really hardly need the feature then you should use it in the form scroll:1 and you have to invest more time in the debugging.
The last remark: I don't recommend usage of gridComplete. I recommend to use loadComplete instead. See the answer for more details.
The last remark: i recommend to use gridview: true in all grids and subgrids which you use.
UPDATED: I am not sure that I full understand which behavior you want to implement in onSelectRow, but the following implementation
onSelectRow: function (rowid) {
var $self = $(this),
$this = $("#" + $.jgrid.jqID(rowid)), // the row
$expanded = $self.find("td.sgexpanded");
if ($expanded.length > 0) {
$expanded.trigger("click");
}
$self.jqGrid("expandSubGridRow", rowid);
$self.jqGrid("setSelection", rowid, false);
$this.closest(".ui-jqgrid-bdiv").scrollTop($this.position().top);
}

Related

how create dynamic multiple jqgrid some page

hi i want create dynamic multiple jqgrid .but create one jqgrid
fisrt dynamic this down html
<div dir='rtl' align='center' class='table - responsive'><div class='row well'>
<table id='dataArray' cellpadding='0' cellspacing='0'></table>
<div id="pager_dataArray"></div>
</div>
</div>
<br />
<div dir='rtl' align='center' class='table - responsive'>
<div class='row well'>
<table id='dataArray2' cellpadding='0' cellspacing='0'></table>
<div id="pager_dataArray2"></div>
</div>
</div>
then use js code for create jqgrid ;plase pay attention iam for get model and header grid call function in js file,
LoadGrid()
data: LoadGrid(),
colNames: getColNames(LoadGrid()[0]),
colModel: getColModels(LoadGrid()[0]),
var searchOptions = ['eq', 'ne', 'lt', 'le', 'gt', 'ge', 'bw', 'bn', 'in', 'ni', 'ew', 'en', 'cn', 'nc'];
$(document).ready(function () {
var d = new Date();
var month = d.getMonth() + 1;
var day = d.getDate();
var today = d.getFullYear() + '/' +
(('' + month).length < 2 ? '0' : '') + month + '/' +
(('' + day).length < 2 ? '0' : '') + day;
$("#dynamicGrouping").change(function () {
var groupingName = $(this).val();
alert(groupingName)
if (groupingName) {
//$('#list').jqGrid('groupingGroupBy', ['AddDate_D', 'Name_c']);
$('#' + gridid).jqGrid('groupingGroupBy', [groupingName]);
} else {
$('#' + gridid).jqGrid('groupingRemove');
}
});
caption: "تست گرید",
$('#' + gridid).jqGrid({
caption: "تست گرید",
//url from wich data should be requested
// url: '#Url.Action("GetProducts","Home")',
datatype: 'local',
//این تابع از فایل androidfunction فراخوانی می شود
data: LoadGrid(),
colNames: getColNames(LoadGrid()[0]),
colModel: getColModels(LoadGrid()[0]),
jsonReader: {
root: "Rows",
page: "Page",
total: "Total",
records: "Records",
repeatitems: true,
userdata: "UserData",
id: "Id",
cell: "RowCells"
},
grouping: true,
iconSet: "glyphIcon",
groupingView: {
// groupField: ['AddDate_D' , 'Name_c'],
groupColumnShow: [true],
groupText: ['<b>{0}</b>'],
groupCollapse: true,
groupOrder: ['asc'],
groupSummary: [true]
},
cmTemplate: { editable: false, autoResizable: true },
toppager: true,
// groupingView: { groupField: ['AddDate_D'] },
mtype: 'POST',
footerrow: true,
// userDataOnFooter : true,
//gridComplete: function () {
// var $grid = $("#FooTable");
// var colSum = $grid.jqGrid('getCol', 'Price_Num', false, 'sum');
// $grid.jqGrid('footerData', 'set', { price: colSum });
//},
pager: $('#' + pagegrid),
//number of rows per page
rowNum: 10,
rowList: [10, 20, 50, 100],
//initial sorting column
sortname: 'Id',
//initial sorting direction
sortorder: 'asc',
// loadonce: true,
shrinkToFit: true,
//we want to display total records count
viewrecords: true,
width: 'auto',
height: 'auto',
hidegrid: false,
direction: "rtl",
gridview: true,
altRows: true,
rownumbers: true,
autoencode: true,
treeGrid: true,
treeGridModel: 'adjacency',
ExpandColClick: true,
// ignoreCase: true,
//loadComplete : function() {
// var table = this;
// setTimeout(function(){
// updatePagerIcons(table);
// }, 0);
//},
loadComplete: function () {
sumarValores($(this))
},
loadError: function (xhr, st, err) {
jQuery("#rsperror").html("Type: " + st + "; Response: " + xhr.status + " " + xhr.statusText);
},
})
.navGrid(
$('#' + pagegrid),
//enabling buttons
{ add: false, del: false, edit: false, search: false },
//edit option
{
width: 'auto', checkOnUpdate: true, checkOnSubmit: true,
beforeShowForm: function (form) {
centerDialog(form, $('#' + gridid));
}
},
//add options
{
width: 'auto', url: '#Url.Action("AddProduct","Home")',
},
//add options
//delete options
{
url: '#Url.Action("DeleteProduct","Home")', reloadAfterSubmit: false
})
.jqGrid('inlineNav', $('#' + pagegrid),
{
// cloneToTop: true,
edit: false, add: true, save: false, cancel: false,
edittext: "ویرایش", addtext: "جدید", savetext: "ذخیره", canceltext: "لغو",
addParams: {
// اگر می‌خواهید ردیف‌های جدید در ابتدا ظاهر شوند، این سطر را حذف کنید
position: "first", //ردیف‌های جدید در آخر ظاهر می‌شوند
rowID: '_empty',
useDefValues: true,
addRowParams: getInlineNavParams(true)
},
editParams: getInlineNavParams(false)
}
)
$('#' + gridid).jqGrid('navButtonAdd', '#list_toppager',
{
caption: ""/*"Show"*/, buttonicon: "ui-icon-extlink", title: "Show Link",
onClickButton: function () {
var grid = $('#' + gridid);
var rowid = grid.jqGrid('getGridParam', 'selrow');
window.location = grid.jqGrid('getCell', rowid, 'dataUrl');
}
});
$('#' + gridid).jqGrid('filterToolbar', {
stringResult: true,//// وجود این سطر سبب می‌شود تا اپراتورها به سرور ارسال شوند
enableClear: false,
searchOnEnter: true,
searchOperators: true, // فعال سازی منوی اپراتورها
defaultSearch: "cn"
});
function getSelectedRow() {
var grid = $('#' + gridid);
var rowKey = grid.jqGrid('getGridParam', "selrow");
if (rowKey)
alert("Selected row primary key is: " + rowKey);
else
alert("No rows are selected");
}
});
function sumarValores($self) {
var sumaHa = 0;
var columnNames = $('#' + gridid).jqGrid('getGridParam', 'colNames');
var global;
var footer = {};
for (var z = 0; z < columnNames.length; z++) {
var colN = columnNames[z];
// $self.jqGrid("footerData", "set", footer);
if (colN == "Price") {
colN = colN.concat('_Num');
var sumtotal = $self.jqGrid("getCol", colN, false, "sum");
// global = colN;
global = 'Price_Num';
footer[global] = sumtotal;
//$self.jqGrid("footerData", "set", {
// Price_Num: sumtotal,
//});
$self.jqGrid("footerData", "set", footer);
break;
}
if (colN == "AddDate") {
global = 'AddDate_D';
var sumtotald = $self.jqGrid("getCol", colN, false, "sum");
// footer[global] = sumtotald;
$self.jqGrid("footerData", "set",
{
AddDate_D: sumtotald,
}
);
}
}
}
function getInlineNavParams(isAdd) {
return {
// استفاده از آدرس‌های مختلف برای حالات ویرایش و ثبت اطلاعات جدید
url: isAdd ? '#Url.Action("AddUser", "Home")' : '#Url.Action("EditUser","Home")',
key: true,
restoreAfterError: false, // این مورد سبب می‌شود تا اعتبارسنجی سمت سرور قابل اعمال شود
oneditfunc: function (rowId) {
// نمایش دکمه‌های ذخیره و لغو داخل همان سطر
$("#jSaveButton_" + rowId).show();
$("#jCancelButton_" + rowId).show();
},
successfunc: function () {
var $self = $(this);
setTimeout(function () {
$self.trigger("reloadGrid"); // دریافت کلید اصلی ردیف از سرور
}, 50);
},
errorfunc: function (rowid, response, stat) {
if (stat != 'error') // this.Response.StatusCode == 200
return;
var result = $.parseJSON(response.responseText);
if (result.success === false) {
//نمایش خطای اعتبار سنجی سمت سرور پس از ویرایش یا افزودن
$.jgrid.info_dialog($.jgrid.errors.errcap,
'<div class="ui-state-error">' + result.message + '</div>',
$.jgrid.edit.bClose,
{ buttonalign: 'center' });
}
}
};
}
function centerDialog(form, grid) {
var dlgDiv = $("#editmod" + grid[0].id);
var parentDiv = dlgDiv.parent(); // div#gbox_list
var dlgWidth = dlgDiv.width();
var parentWidth = parentDiv.width();
var dlgHeight = dlgDiv.height();
var parentHeight = parentDiv.height();
var parentTop = parentDiv.offset().top;
var parentLeft = parentDiv.offset().left;
dlgDiv[0].style.top = Math.round(parentTop + (parentHeight - dlgHeight) / 2) + "px";
dlgDiv[0].style.left = Math.round(parentLeft + (parentWidth - dlgWidth) / 2) + "px";
}
function getColNames(data, status) {
var keys = [];
if (status != 'headr') {
for (var key in data) {
if (data.hasOwnProperty(key)) {
keys.push((key.split('_'))[0]);
}
}
keys.push('');
}
else {
for (var key in data) {
if (data.hasOwnProperty(key)) {
keys.push(key);
}
}
keys.push('');
}
return keys;
}
function getColModels(data) {
var colNames = getColNames(data, 'headr');
var colModelsArray = [];
for (var i = 0; i < colNames.length; i++) {
var str;
if (i === 0) {
str = {
name: (colNames[i]),
index: (colNames[i]),
key: true,
editable: false,
search: false,
width: 20,
};
} else if (i >= 1 && i <= colNames.length - 2) {
switch ((colNames[i].split('_'))[1]) {
case ('Num'):
str = {
name: (colNames[i]),
index: (colNames[i]),
editable: true,
summaryType: 'sum', summaryTpl: '<b>جمع مشاهدات: {0}</b>',
//width: 100,
searchoptions: { sopt: searchOptions },
formatter: 'currency',
formatoptions:
{
decimalSeparator: '.',
thousandsSeparator: ',',
decimalPlaces: 0,
prefix: 'ريال'
},
editable: true, edittype: 'text',
// summaryType: function (val, name, record) {
};
// tt = 'Price_Num';
break;
case ('D'):
str = {
name: (colNames[i]),
index: (colNames[i]),
editable: true,
// width: 100,
searchoptions: {
dataInit: function (elem) {
$(elem).datepicker({
dateFormat: 'm/d/y',
onClose: function (event) {
$('#' + gridid).trigger("reloadGrid", [{ page: 1 }]);
}
});
// datepicker({
// dateFormat: 'dd/mm/yy',
// changeYear: true,
// changeMonth: true,
// showWeek: true,
// onSelect: function (dateText, inst) {
// setTimeout(function () {
// $('#' + gridid)[0].triggerToolbar();
// }, 100);
// }
//});
},
dataInit: function (elem) {
$(elem).datepicker({
dateFormat: 'm/d/y',
onClose: function (event) {
$('#' + gridid).trigger("reloadGrid", [{ page: 2 }]);
}
});
}
, sopt: searchOptions
},
editoptions: {
maxlength: 10,
onclick: 'PersianDatePicker.Show(this,' + '1395/02/01' + ')'
},
editrules: {
required: true
}
};
break;
case ('c'):
str = {
name: (colNames[i]),
index: (colNames[i]),
editable: true,
//width:100,
searchoptions: { sopt: searchOptions },
};
break;
default:
// alert('>41');
}
}
else {
str = {
name: 'myac',
index: colNames[i],
resize: false,
fixed: true, sortable: false,
formatter: 'actions',
search: false,
formatoptions: {
keys: true
},
}
}
//formatter: 'currency',
//formatoptions:
//{
// decimalSeparator: '.',
// thousandsSeparator: ',',
// decimalPlaces: 2,
// prefix: '$'
//},
//editable: true, edittype: 'text',
colModelsArray.push(str);
}
return colModelsArray;
}
function updatePagerIcons(table) {
//var replacement =
//{
// 'ui-icon-seek-first': 'ace-icon fa fa-angle-double-left bigger-140',
// 'ui-icon-seek-prev': 'ace-icon fa fa-angle-left bigger-140',
// 'ui-icon-seek-next': 'ace-icon fa fa-angle-right bigger-140',
// 'ui-icon-seek-end': 'ace-icon fa fa-angle-double-right bigger-140'
//};
//$('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function () {
// var icon = $(this);
// var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
// if ($class in replacement) icon.attr('class', 'ui-icon ' + replacement[$class]);
//})
}
$(document).ready(function () {
function LoadGrid() {
object = {
"dataArray":
[
{ id_R: 1, Name_c: "dummy1", AddDate_D: "1394/07/27", Price_Num: "10000" },
{ id_R: 2, Name_c: "dummy2", AddDate_D: "1394/07/28", Price_Num: "120000" },
],
"dataArray2":
[
{ id_R: 9, Name2_c: "dummy9", AddDate2_D: "1393/04/28", Price2_Num: "200000" },
{ id_R: 10, Name_c: "dummy10", AddDate_D: "1393/04/04", Price_Num: "2100000" },
]
};
// برای مپ کردن ارایه یه ارایه دیگر
//departement = $.map(dataArray, function (value, index) {
// return [value];
//});
var names = Object.getOwnPropertyNames(object);
// var names = 'grd1'
var col = [];
var gridarr = [];
var pagegrarr = [];
//مقادیر ارایه را در متغیر زیر می ریزد
var col = Object.values(object);
//تعداد ارایه برای گرید بدست اوردیم
var countarr = col.length;
for (var i = 0; i < countarr; i++) {
//اسم جدول گرید
gridarr[i] = names[i];
pagegrarr[i] = 'pager_' + names[i];
// return col[i];
}
flag++;
switch (flag) {
case 1:
case 2:
case 3:
case 4:
gridid = gridarr[0]
pagegrid = pagegrarr[0]
return col[0];
break;
case 5:
case 6:
case 7:
case 8:
gridid = gridarr[1]
pagegrid = pagegrarr[1]
return col[1];
break;
default:
break;
}
}
});
this answer:
<script>
$(document).ready(function () {
function grid(tt) {
//=== LOCA VARIABLES ===//$.jgrid.randId()
var myGrid = $("<table>").attr("id", tt);
var myPager = $("<div>").attr("id", tt +"_pager");
var localData1 = {
"page": 1,
"totalRecords": 5,
"pageSize": 3,
"rows": [
{ Name: "Name 1" },
{ Name: "Name 3" },
{ Name: "Name 2" }
]
};
function publicInit() {
$("body").append(myGrid, myPager);
myGrid.jqGrid({
pager: myPager,
data: localData1.rows,
datatype: "local",
colModel: [
{ name: 'Name', index: 'Name', width: "500" }
],
//localReader: {
// repeatitems: false
// },
// rowNum: 3,
viewrecords: true,
height: "auto",
ignoreCase: true
});
}
//=== REVEALING PATTERN===//
return {
init: publicInit
}
};
var grid1 = new grid("y");
grid1.init();
$("body").append("<br><br>"); //Add some spacing to distinguish between both grids
var grid2 = new grid("c");
grid2.init();
$("body").append("<br><br>"); //Add some spacing to distinguish between both grids
var grid2 = new grid("b");
grid2.init();
});
</script>

jqGrid width subgrid pager exceeds main grid width

I hope my title is comprehensive !
I am developing my own personal account with one main grid and one grid as subgrid.
The trouble is that main grid pager is displayed fine, but subgrid pager exceeds the width of grid, such as below :
I don't understand what is wrong.
Here is the subgrid code :
subGridRowExpanded: function(subgrid_id, row_id) {
var rowdata = $("#jqGrid").jqGrid('getRowData',row_id),
catg=rowdata.cg_id,
subgrid_table_id = subgrid_id+"_t",
pager_id = "p_"+subgrid_table_id;
$("#"+subgrid_id).closest("td").attr("colspan", 20)
.css({
borderRight:0,
borderLeft:0,
padding:0
})
.parent().find('td:eq(0)')
.addClass('ui-widget-content')
.addClass('ui-state-highlight')
.css({
borderLeft:0,
borderTop:0
});
$("#"+subgrid_id).html("<table id='"+subgrid_table_id+"' class='scroll'></table><div id='"+pager_id+"'></div>");
$("#"+subgrid_table_id).jqGrid({
url:"subc.php?rowid="+row_id+"&catg="+catg,
idPrefix:'s_'+row_id+'_',
datatype: "json",
colNames: ["ID","id_cp","Nom du poste"],
colModel:[
{
name:"su_id",
hidden:true
},
{
name:"id_cg",
hidden:true
},
{
name:"su_name"
}
],
caption:"Liste des postes budgétaires",
hidegrid: false,
gridview: true,
autowidth:true,
shrinkToFit:false,
viewrecords: true,
recordtext: "Postes {0} - {1} of {2}",
emptyrecords: "Aucun poste à afficher",
rownumbers:true,
rownumWidth:40,
altRows:false,
height:"auto",
maxHeight: (23*15),
rowNum: 20,
pager: pager_id,
loadComplete: function(){
$("#gview_"+subgrid_table_id+" .ui-jqgrid-titlebar .ui-jqgrid-title").css({color:'#875', fontWeight:'bold', fontSize:'1.2rem', lineHeight:'1.3rem',marginLeft:'10px'});
}
});
$("#"+subgrid_table_id).jqGrid('navGrid',"#"+pager_id,{search:false});
}
I'm sure that's a newbie mistake, and I hope somebody could help me.
Many thanks in advance
Cheers
JiheL

Cancel edit event in jqGrid inline edit

I'm using jqgrid inline edit in which i have a scenario to invoke the "cancel edit" button event and throw a message "Are you sure to cancel?".
//Code:
//Unload the grid.
$('#CommentsData').jqGrid('GridUnload');
//Comments grid start.
$("#CommentsData").jqGrid({
datastr: tableSrc,
hoverrows: false,
datatype: "jsonstring",
jsonReader: {
id: 'CommentId',
repeatitems: false
},
height: 'auto',
width: 'auto',
hidegrid: false,
gridview: true,
sortorder: 'desc',
sortname: 'DateTime',
pager: '#CommentsPager',
rowList: [], // disable page size dropdown
pgbuttons: false, // disable page control like next, back button
pgtext: null, // disable pager text like 'Page 0 of 10'
viewrecords: false, // disable current view record text like 'View 1-10 of 100'
caption: "Comments",
colNames: ['DateTime', 'UserName', 'Comments'],
colModel: [
{
name: 'DateTime', index: 'DateTime', width: 120, formatter: "date", sorttype: "date",
formatoptions: { srcformat: "ISO8601Long", newformat: "m/d/Y h:i A" }
},
{ name: 'UserName', index: 'UserName' },
{ name: 'CommentText', index: 'CommentText', editable: true }],
//Events to add and edit comments.
serializeRowData: function (postdata) {
var filterResult;
var jsonResult;
if (tableSrc == "")
jsonResult = $.parseJSON(commentDetails);
else
//Parse values bind to the comments.
jsonResult = $.parseJSON(tableSrc);
var newResult = new Object();
//Check if operation is edit.
if (postdata.oper == "edit") {
//Filter the edited comments from main source.
newResult = Enumerable.From(jsonResult).Where(function (s) { return s.CommentId = postdata.id }).First();
newResult.CommentText = postdata.CommentText;
}
else {
filterResult = Enumerable.From(jsonResult).First();
newResult.CommentText = postdata.CommentText;
newResult.TransactionId = filterResult.TransactionId;
newResult.TaskId = filterResult.TaskId;
}
filterResult = JSON.stringify(newResult);
$.ajax({
url: '#Url.Action("UpdateComments", "Home")',
datatype: 'json',
data: { 'resultData': filterResult, 'action': postdata.oper },
type: 'POST',
success: OnCompleteComments,
error: function (xhr, status, error) {
if (xhr.statusText == "Session TimeOut/UnAuthorized") {
alert(xhr.statusText);
window.location.href = '#Url.Action("LogOut", "Account")';
}
else
alert(xhr.responseText);
}
});
//After update Load the grid.
function OnCompleteComments(result) {
selectTaskComment = false;
$('#dialog').dialog("close");
myfilter = $("#TransactionsGrid").jqGrid("getGridParam", "postData").filters;
rowList = $('.ui-pg-selbox').val();
Loadgrid($("#TransactionsGrid").getGridParam('page'));
}
},
onSelectRow: function (id) {
selectTaskComment = true;
var thisId = $.jgrid.jqID(this.id);
$("#" + thisId + "_iledit").removeClass('ui-state-disabled');
$("#del_" + thisId).removeClass('ui-state-disabled');
var selectValues = jQuery('#CommentsData').jqGrid('getRowData', id);
thisId = $.jgrid.jqID(this.id);
if (selectValues.UserName == '#ViewBag.UserName' || '#ViewBag.IsAdmin' == 'True') {
$("#" + thisId + "_iledit").removeClass('ui-state-disabled');
$("#del_" + thisId).removeClass('ui-state-disabled');
}
else {
$("#" + thisId + "_iledit").addClass('ui-state-disabled');
$("#del_" + thisId).addClass('ui-state-disabled');
}
}
});
jQuery("#CommentsData").jqGrid('navGrid', '#CommentsPager', { edit: false, add: false, del: true, search: false, refresh: false }, {}, {},
{
//Delete event for comments
url: '#Url.Action("UpdateComments", "Home")',
serializeDelData: function (postData) {
return {
resultData: JSON.stringify(postData.id),
action: JSON.stringify(postData.oper),
}
},
errorTextFormat: function (xhr) {
if (xhr.statusText == "Session TimeOut/UnAuthorized") {
window.location.href = '#Url.Action("LogOut", "Account")';
} else {
return xhr.responseText;
}
},
beforeSubmit: function () {
myfilter = $("#TransactionsGrid").jqGrid("getGridParam", "postData").filters;
return [true, '', ''];
},
afterSubmit: function (response, postdata) {
selectTaskComment = false;
Loadgrid($("#TransactionsGrid").getGridParam('page'));
return [true, '', ''];
}
});
$('#CommentsData').jqGrid('inlineNav', '#CommentsPager', { edit: true, add: true, save: true, del: false, cancel: true });
$("#CommentsData_iledit").addClass('ui-state-disabled');
$("#del_CommentsData").addClass('ui-state-disabled');
In which event i have to write the code and throw the alert message?
Also if possible, need to know if the above code could be optimized. Because the delete event is written in a separate place comparing edit and add. I'm bit confused if this is right method.
The easiest way to invoke the "cancel edit" button would be executing the code
$("#CommentsData_ilcancel").click(); // trigger click event on Cancel button
where CommentsData is the id of the grid.

jqGrid hidden plus/minus/open icon column make subgrid less wide as main row

Following to this post about hiding plus/minus/open icon column, I have applied these suggests, so in CSS file :
.subgrid-cell { display: none; }
All is OK :
but the subgrid don't fill the width of right column of main grid.
Please, is there a mistake in my code,
jQuery(document).ready(function ($) {
var OldSelectedRow=null;
var height=$('body').height()-210;
var numRows=Math.floor(height/23)-(Math.floor(height/23)%5);
var heightRows=numRows*23;
var myGrid = $("#tab22");
myGrid.jqGrid({
caption:"Recherche d'un ARTICLE dans les PARCS CLIENTS",
hidegrid:false,
url:'sub22.php',
datatype: "json",
height:heightRows,
shrinkToFit: true,
rowNum:numRows,
rownumbers:true,
rownumWidth: 40,
gridview: true,
colNames:['Id','Code', 'Désignation', 'Famille','S/famille','Marque','Matière','Réf.constructeur','PV base'],
colModel:[
{name:'a.id',index:'a.id', width:60, align:"right",hidden:true},
{name:'a.code',index:'a.code', width:150},
{name:'a.descr',index:'a.descr', width:200},
{name:'f.code',index:'f.code', width:80},
{name:'s.code',index:'s.code', width:80},
{name:'k.code',index:'k.code', width:80},
{name:'m.code',index:'m.code', width:80},
{name:'a.refc',index:'a.refc', width:150},
{name:'t.pnc',index:'t.pnc', width:80, align:"right"}
],
pager: '#tab22p',
sortname: 'a.code',
sortorder: "asc",
viewrecords: true,
emptyrecords: 'Aucune donnée correspondante...',
altRows:true,
altclass:'myAltRowClass',
onSortCol: function (index, idxcol, sortorder) {
// montre la colonne sélectionnée pour le tri de la grille
if (this.p.lastsort >= 0 && this.p.lastsort !== idxcol
&& this.p.colModel[this.p.lastsort].sortable !== false) {
$(this.grid.headers[this.p.lastsort].el).find(">div.ui-jqgrid-sortable>span.s-ico").show();
$(this.grid.headers[this.p.lastsort].el).removeClass('ui-state-active');
}
$(this.grid.headers[idxcol].el).addClass('ui-state-active');
},
gridComplete:function(){
OldSelectedRow=null;
colModel = myGrid.jqGrid('getGridParam', 'colModel');
sortName = myGrid.jqGrid('getGridParam', 'sortname');
$('#gbox_' + $.jgrid.jqID(myGrid[0].id) +
' tr.ui-jqgrid-labels th.ui-th-column').each(function (i) {
var cmi = colModel[i], colName = cmi.name;
if (cmi.sortable !== false) {
$(this).find('>div.ui-jqgrid-sortable>span.s-ico').show();
} else if (!cmi.sortable && colName !== 'rn' && colName !== 'cb' && colName !== 'subgrid') {
$(this).find('>div.ui-jqgrid-sortable').css({cursor: 'default'});
}
if (cmi.name === sortName) {
$(this).addClass('ui-state-active');
//alert(i);
var gridId = myGrid.jqGrid('getDataIDs');
for (var countRow = 0; countRow < gridId .length; countRow ++)
{
var rowId = gridId [countRow ];
var dataFromTheRow = myGrid.jqGrid ('getRowData', rowId);
myGrid.jqGrid('setCell',rowId, i, '','ui-widget-header');
myGrid.jqGrid('setCell',rowId, i, '',{'border-top':0,'border-left':0});
}
}
});
},
onSelectRow:function(id,status){
if(OldSelectedRow!=id){
if(OldSelectedRow!=null){
myGrid.jqGrid ('collapseSubGridRow', OldSelectedRow);
$('#tab22_'+OldSelectedRow+'_t').remove();
$('#'+OldSelectedRow).removeClass('ui-state-highlight');
}
$('#'+id).addClass('ui-state-highlight');
OldSelectedRow=id;
myGrid.jqGrid('expandSubGridRow',id);
}else{
myGrid.jqGrid ('collapseSubGridRow', id);
$('#tab22'+id+'_t').remove();
$('#'+id).removeClass('ui-state-highlight');
OldSelectedRow=null;
}
},
subGrid: true,
subGridRowExpanded: function(subgrid_id, row_id) {
rowdata = $("#tab22").jqGrid('getRowData',row_id);
var art=rowdata['a.id'],lastId;
var subgrid_table_id, pager_id;
subgrid_table_id = subgrid_id+"_t";
pager_id = "p_"+subgrid_table_id;
$("#"+subgrid_id).html("<table id='"+subgrid_table_id+"' class='scroll'></table><div id='"+pager_id+"' class='scroll'></div>");
$("#"+subgrid_table_id).jqGrid({
url:"sg22.php?id="+row_id+"&art="+art,
datatype: "json",
colNames: ['Id','Groupe','Client', 'Nom','Ville','Matériel','Marque','Machine','Série','Type','Modèle','Désignation','N° série'],
colModel: [
{name:'p.id',index:'p.id', width:60, align:"right",hidden:true},
{name:'g.code',index:'g.code', width:80},
{name:'c.code',index:'c.code', width:60},
{name:'c.descr',index:'c.descr', width:200},
{name:'c.ville',index:'c.ville', width:200},
{name:'q.code',index:'q.code',width:80},
{name:'k.code',index:'k.code', width:80},
{name:'2h.code',index:'2h.code', width:60},
{name:'2s.code',index:'2s.code', width:60},
{name:'2t.code',index:'2t.code', width:60},
{name:'2m.code',index:'2m.code', width:60},
{name:'2m.descr',index:'2m.descr', width:200},
{name:'p.numserie',index:'p.numserie', width:80}
],
pager: pager_id,
rownumbers: true,
rowNum:15,
rowNumWidth:40,
viewrecords: true,
emptyrecords: 'Aucune donnée correspondante...',
caption:"Liste des PARCS CLIENTS contenant l'ARTICLE sélectionné",
hidegrid:false,
rownumWidth: 40,
autowidth:true,
altRows:true,
altclass:'myAltRowClass',
sortname: 'c.code',
sortorder: "asc",
height: 345,
onSortCol: function (index, idxcol, sortorder) {
// montre la colonne sélectionnée pour le tri de la grille
if (this.p.lastsort >= 0 && this.p.lastsort !== idxcol
&& this.p.colModel[this.p.lastsort].sortable !== false) {
$(this.grid.headers[this.p.lastsort].el).find(">div.ui-jqgrid-sortable>span.s-ico").show();
$(this.grid.headers[this.p.lastsort].el).removeClass('ui-state-active');
}
$(this.grid.headers[idxcol].el).addClass('ui-state-active');
},
onSelectRow:function(id,status){
if(lastId!=id){
if(lastId!=null){
$("#"+subgrid_table_id).jqGrid ('collapseSubGridRow', lastId);
$('#'+subgrid_table_id+'t').remove();
$('#'+id).removeClass('ui-state-highlight');
}
$('#'+id).addClass('ui-state-highlight');
}
lastId=id;
$("#"+subgrid_table_id).jqGrid('expandSubGridRow',id);
},
gridComplete:function(){
// montre la colonne triée au chargement des données
colModel = $("#"+subgrid_table_id).jqGrid('getGridParam', 'colModel');
sortName = $("#"+subgrid_table_id).jqGrid('getGridParam', 'sortname');
$('#gbox_' + $.jgrid.jqID($("#"+subgrid_table_id)[0].id) +
' tr.ui-jqgrid-labels th.ui-th-column').each(function (i) {
var cmi = colModel[i], colName = cmi.name;
if (cmi.sortable !== false) {
$(this).find('>div.ui-jqgrid-sortable>span.s-ico').show();
} else if (!cmi.sortable && colName !== 'rn' && colName !== 'cb' && colName !== 'subgrid') {
$(this).find('>div.ui-jqgrid-sortable').css({cursor: 'default'});
}
if (cmi.name === sortName) {
$(this).addClass('ui-state-active');
var gridId = $("#"+subgrid_table_id).jqGrid('getDataIDs');
for (var countRow = 0; countRow < gridId .length; countRow ++)
{
var rowId = gridId [countRow ];
var dataFromTheRow = $("#"+subgrid_table_id).jqGrid ('getRowData', rowId);
$("#"+subgrid_table_id).jqGrid('setCell',rowId, i, '','ui-widget-header');
$("#"+subgrid_table_id).jqGrid('setCell',rowId, i, '',{'border-top':0,'border-left':0});
}
}
});
},
subGrid: true,
subGridRowExpanded: function(subgrid2_id, row2_id) {
rowdata = $(this).jqGrid('getRowData',row2_id);
var parc=rowdata['p.id'],lastId=null;
var subgrid2_table_id, pager2_id;
subgrid2_table_id = subgrid2_id+"_tt";
pager2_id = "p_"+subgrid2_table_id;
$("#"+subgrid2_id).html("<table id='"+subgrid2_table_id+"' class='scroll'></table><div id='"+pager2_id+"' class='scroll'></div>");
$("#"+subgrid2_table_id).jqGrid({
url:"sg22b.php?id="+row2_id+"&parc="+parc,
datatype: "json",
caption:"Détail du PARC",
hidegrid:false,
colNames:['Id','Ensemble','Article', 'Désignation', 'Famille','S/Famille','Matière','PV base','% Remise','PV net'],
colModel:[
{name:'a.id',index:'a.id', width:60, align:"right",hidden:true},
{name:'c.code',index:'c.code', width:100,sortable:false},
{name:'a.code',index:'a.code', width:100,sortable:false},
{name:'a.descr',index:'a.descr', width:400,sortable:false},
{name:'f.code',index:'f.code', width:80,sortable:false},
{name:'s.code',index:'s.code', width:80,sortable:false},
{name:'m.code',index:'m.code', width:80,sortable:false},
{name:'t.pnc',index:'t.pnc', width:80,align:'right',sortable:false},
{name:'rem',index:'rem', width:80,align:'center',sortable:false},
{name:'pv',index:'pv', width:80,align:'right',sortable:false}
],
pager: pager2_id,
rownumbers: true,
viewrecords: true,
emptyrecords: 'Aucune donnée correspondante...',
rownumWidth: 40,
altRows:true,
altclass:'myAltRowClass',
sortname: 'c.code',
sortorder: "asc",
scroll:true,
maxheight: 230,
onSortCol: function (index, idxcol, sortorder) {
// montre la colonne sélectionnée pour le tri de la grille
if (this.p.lastsort >= 0 && this.p.lastsort !== idxcol
&& this.p.colModel[this.p.lastsort].sortable !== false) {
$(this.grid.headers[this.p.lastsort].el).find(">div.ui-jqgrid-sortable>span.s-ico").show();
$(this.grid.headers[this.p.lastsort].el).removeClass('ui-state-active');
}
$(this.grid.headers[idxcol].el).addClass('ui-state-active');
},
gridComplete:function(){
// montre la colonne triée au chargement des données
colModel = $("#"+subgrid2_table_id).jqGrid('getGridParam', 'colModel');
sortName = $("#"+subgrid2_table_id).jqGrid('getGridParam', 'sortname');
$('#gbox_' + $.jgrid.jqID($("#"+subgrid2_table_id)[0].id) +
' tr.ui-jqgrid-labels th.ui-th-column').each(function (i) {
var cmi = colModel[i], colName = cmi.name;
if (cmi.sortable !== false) {
$(this).find('>div.ui-jqgrid-sortable>span.s-ico').show();
} else if (!cmi.sortable && colName !== 'rn' && colName !== 'cb' && colName !== 'subgrid') {
$(this).find('>div.ui-jqgrid-sortable').css({cursor: 'default'});
}
if (cmi.name === sortName) {
$(this).addClass('ui-state-active');
var gridId = $("#"+subgrid2_table_id).jqGrid('getDataIDs');
for (var countRow = 0; countRow < gridId .length; countRow ++)
{
var rowId = gridId [countRow ];
var dataFromTheRow = $("#"+subgrid2_table_id).jqGrid ('getRowData', rowId);
$("#"+subgrid2_table_id).jqGrid('setCell',rowId, i, '','ui-widget-header');
$("#"+subgrid2_table_id).jqGrid('setCell',rowId, i, '',{'border-top':0,'border-left':0});
}
}
});
}
})
$("#"+subgrid2_table_id).jqGrid('navGrid',"#"+pager2_id,{edit:false,add:false,del:false,search:false});
$("#"+subgrid2_table_id).jqGrid('filterToolbar',{stringResult: true,searchOnEnter : false});
}
});
$("#"+subgrid_table_id).jqGrid('navGrid',"#"+pager_id,{edit:false,add:false,del:false,search:false});
$("#"+subgrid_table_id).jqGrid('filterToolbar',{stringResult: true,searchOnEnter : false});
$("#"+subgrid_table_id).jqGrid('hideCol', 'subgrid');
},
subGridRowColapsed: function(subgrid_id, row_id) {
// this function is called before removing the data
var subgrid_table_id;
subgrid_table_id = subgrid_id+"_t";
$("#"+subgrid_table_id).remove();
myGrid.jqGrid('resetSelection');
}
});
myGrid.jqGrid('navGrid','#tab22p',{search:false,del:false,edit:false,add:false});
myGrid.jqGrid('filterToolbar',{stringResult: true,searchOnEnter : false});
myGrid.closest("div.ui-jqgrid-view")
.children("div.ui-jqgrid-titlebar")
.css({
textAlign: "center"
})
.children("span.ui-jqgrid-title")
.css({
float: "none",
color:'red',
fontSize:'16px'
});
myGrid.jqGrid('hideCol', 'subgrid');
$(window).bind('resize', function() {
myGrid.jqGrid('setGridWidth',$('body').width()-22);
var height=$('body').height()-210;
numRows=Math.floor(height/23)-(Math.floor(height/23)%5);
heightRows=numRows*23;
myGrid.jqGrid('setGridParam', {height:heightRows,rowNum:numRows});
myGrid.jqGrid('setGridHeight',heightRows);
myGrid.trigger("reloadGrid");
}).trigger('resize');});
or is there some way to solve or turnaround this trouble ?
Many thanks to whose who could bring me some help. have a nice day
JiheL
If I understand correct your question you can fix the problem by adding
autowidth: true
option to both subgrids (see two callbacks subGridRowExpanded which you use).
I recommend you additionally to verify your code with respect of tools like JSLint or JSHint. You would see that your code use many undefined variables (colModel, sortName, rowdata). Additionally it's strictly recommended to use idPrefix option in jqGrid with subgrids to prevent possible id duplicates.
UPDATED: After you posted the fiddler demo I understand the problem. To fix it I suggest to set colspan attribute on the <td> having subgrid-data class. For example one can include in subGridRowExpanded callback the line
$("#" + subgrid_id).closest("td").attr("colspan", 3);
in your demo to fix the problem. See http://jsfiddle.net/Cs9CP/11/ (or the full screen demo). Additionally I recommend to use height: "auto" for all subgrids. As the result you will see something like
If you want you can additionally hide the first empty column in the subgrid with the line
$("# + subgrid_id).closest(".ui-subgrid").find("td[colspan=1]").first().hide();
See http://jsfiddle.net/Cs9CP/12/ (or the full screen demo):

JQGrid : subgrid as a GRID with a navigation bar

I am using JQGrid and displaying subGrid as a JQGRID itself.
I was wondering if there is a way to display the navigation bar for the subgrid too.
I tried following the way its being done for JQGrid, but in vain.
Thanks in advance!
Make sure that in the subGrid jqGRid function you also set the pager property to the pager id in the subgrid
... subGrid: true,
subGridRowExpanded: function(subgrid_id, row_id)
{
var subgrid_table_id;
var pager_id;
subgrid_table_id = subgrid_id+"_t";
pager_id = "p_"+subgrid_table_id;
$("#" + subgrid_id).html("<table id='"+subgrid_table_id+"' class='scroll'></table><div id='"+ pager_id +"' class='scroll'></div>");
$("#" + subgrid_table_id).jqGrid({
url:"ListSub/"+ row_id,
datatype: "json",
colNames: ['Street1','Street2','Street3','Zip','Place','Country'],
colModel:
[
{name:"Street1",index:"Street1",width:80,key:true, editable:true},
{name:"Street2",index:"Street2",width:130, editable:true},
{name:"Street3",index:"Street3",width:80,align:"right", editable:true},
{name:"Zip",index:"Zip",width:80,align:"right", editable:true},
{name:"Place",index:"Place",width:100,align:"right", editable:true},
{name:"Country",index:"Country",width:100,align:"right", editable:true}
],
caption: "Offices",
height: "100%",
rowNum:10,
sortname: 'Street1',
sortorder: "asc",
pager:pager_id
});
jQuery("#"+subgrid_table_id).jqGrid('navGrid',"#"+pager_id,{edit:false,add:false,del:false,search:false})
}....
subGrid: true,
subGridRowExpanded: function(ParentGridID, rowid) {
var datagridSub, navGrid;
SubGridID = ParentGridID+"_t";
//alert(rowid);
navGrid = "p_"+datagridSub;
$("#"+ParentGridID).html("<table id='"+SubGridID+"' class='scroll'></table><div id='"+PagerID+"' class='scroll'></div>");
jQuery("#"+SubGridID).jqGrid({
url:'service url'+rowid,
datatype: "json",
type: "GET",
colNames: ['Id','MID','VendorCode1','VendorCode2','Percentage'],
width:700,
colModel: [
{name:"id",index:"id",width:30},
{name:"mid",index:"mid",width:30},
{name:"vendorcode1",index:"vendorcode1",width:40},
{name:"vendorcode2",index:"vendorcode2",width:40},
{name:"percentage",index:"percentage",width:70}
],
jsonReader: {
repeatitems: false, // To Bind the Data in Grid, if it is JSON format.
id: "id",
root: function (obj) { return obj; } // To Bind the Data in Grid.
// page: function () { return 1; },
//total: function () { return 1; },
//records: function (obj) { return obj.length; },
},
rowNum:20,
pager: '#PagerID',
sortname: 'num',
sortorder: "asc",
postData: {id: rowid},
height: '120%',
});
}

Resources